问题描述
如何采用一个Mongo query、使用以下query查询得到正确结果?
// full documents
[
{ id: 1, category: 'computer', value: 1 },
{ id: 2, category: 'computer', value: 2 },
{ id: 3, category: 'book', value: 2 },
]
// query
const query = [
{ category: 'computer', value: 1 },
{ category: 'book', value: 2 }
]
期待输出:
[
{ id: 1, category: 'computer', value: 1 },
{ id: 3, category: 'book', value: 2 },
]
问题出现的平台版本及自己尝试过哪些方法
技术栈:JavaScript、Node 12、mongoose 4.11
项目组现在采用的方式是如下方法,即使用一个循环把query先map出来,再对每个对象作一一查询操作,但产品环境上可能同时查询许多记录,循环速度稍慢。
await Promise.all(
query.map(({ category, value }) => {
return db.collection.update(
{ category, value },
{ $set: { visitor: ['some-label'] }}
)
})
)
我们还尝试过使用$in
操作符,但这样可能多筛选出一些结果,并不是我们期望的效果。
db.collection.update(
{
category: { $in: query.map(one => one.category) },
value: { $in: query.map(one => one.value) },
},
{ $set: { visitor: ['some-label'] } }
)
感谢大佬们热心解答!
用$match 跟 $or直接出结果。不过你们的数据这么设计有效率问题。