MongoDB如何查询products数组包含指定产品ID列表的所有分类
MongoDB关联分类查询方案
核心逻辑
你需要用到MongoDB的$in运算符,当查询对象为数组字段时,$in会自动匹配所有字段数组中包含至少一个查询数组内元素的文档,完全符合你的需求。
完整JS实现代码
const { MongoClient } = require('mongodb'); // 替换为实际MongoDB连接地址 const MONGODB_URI = 'mongodb://localhost:27017'; // 替换为实际数据库名 const DB_NAME = '你的数据库名称'; async function queryRelatedCategories(productIdList) { const client = new MongoClient(MONGODB_URI); try { await client.connect(); const categoriesCol = client.db(DB_NAME).collection('categories'); // 核心查询语句 return await categoriesCol.find({ products: { $in: productIdList } }).toArray(); } finally { await client.close(); } } // 调用示例 const targetProductIds = ["42221+343211111sj", "43939€jsjakaljwiwjn3"]; queryRelatedCategories(targetProductIds).then(console.log);
注意事项
如果你的产品ID存储为MongoDB内置的ObjectId类型而非字符串,需要先将传入的ID列表转换为对应类型再查询,避免类型不匹配导致无查询结果:
const { ObjectId } = require('mongodb'); const targetProductIds = ["60d21b4667d0d8992e610c85", "60d21b4667d0d8992e610c86"].map(id => new ObjectId(id));
内容的提问来源于stack exchange,提问作者MMilanov
相关产品推荐
相关产品推荐

