You need to enable JavaScript to run this app. MongoDB如何查询products数组包含指定产品ID列表的所有分类
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:57:01