如何在MongoDB中用$in操作符匹配多键对象的组合条件
MongoDB聚合$match阶段匹配多字段组合的正确写法
你之前的查询失败是因为test_and_output是一个不存在的字段,MongoDB无法找到对应匹配的数据。以下两种方法可以实现你需要的“匹配test和output特定组合”的需求:
方法一:用$or搭配多组精准匹配
每个$or的子条件都是同时指定test和output的键值对,每个子条件代表“test等于某值且output等于对应值”的组合,$or会匹配满足任意一组组合的文档:
await SampleCollection.aggregate( [ { $match: { $or: [ { test: 'test01', output: 0 }, { test: 'test03', output: 1 } ] }, }, ], async function (err, data) { if (err) return reject(err); if (!data || !data.length) return resolve(null); if (data.length) return resolve(data); } );
方法二:用$expr结合$in实现组合匹配
如果更倾向于使用$in的写法,可以通过$expr在聚合表达式中,将当前文档的test和output字段组合成对象,再判断该对象是否在目标组合数组中:
await SampleCollection.aggregate( [ { $match: { $expr: { $in: [ { test: "$test", output: "$output" }, [{ test: 'test01', output: 0 }, { test: 'test03', output: 1 }] ] } }, }, ], async function (err, data) { if (err) return reject(err); if (!data || !data.length) return resolve(null); if (data.length) return resolve(data); } );
两种方法都能满足需求:第一种写法更直观,MongoDB可以更好地利用test和output字段的索引;第二种写法更贴合你想用$in的思路,适合组合条件较多的场景。
内容的提问来源于stack exchange,提问作者CODEHUB
相关产品推荐
相关产品推荐

