[英]Mongodb IN and return elements not matched
I have a collection of players
like this:我有一个这样的players
集合:
{
"_id": ObjectId("5eb93f8efd259cd7fbf49d55"),
"id_test": 132
"name": "John Doe"
},
{
"_id": ObjectId("5eb93f8efd259cd7fbf49d33"),
"id_test": 90
"name": "Tom White"
},
{
"_id": ObjectId("5eb93f8efd259cd7fbf49d31"),
"id_test": 999
"name": "Mike Barry"
}
I have an array of Ids with id_test
:我有一个带有id_test
的 ID 数组:
const arrayIds = [ 132, 43, 90, 555];
Then I want to get elements not matched in array (not in collection with $nin).然后我想获取数组中不匹配的元素(不在 $nin 的集合中)。 Im my example I need to output: [43, 555]
我的例子我需要 output: [43, 555]
Something like this: (but I want to know if it's possible with one single query):像这样:(但我想知道是否可以通过一个查询):
const players = await db.collection('players').find(
{ id_test: { "$in": arrayIds } } )
.toArray();
const playersIds = players.map(e => e.id_test); // [132, 90]
const final = arrayIds.filter(i => !playersIds.includes(i)) // [43, 555]
Yes, you can do that in a single query by aggregation,是的,您可以通过聚合在单个查询中执行此操作,
First, we search the players, then create an array of their id_test, then by $setDifference get the difference you want首先,我们搜索玩家,然后创建他们的 id_test 数组,然后通过$setDifference得到你想要的差异
const players = await db.collection('players').aggregate(
[ { $match :
{
id_test : { "$in": arrayIds }
}
},
{
$group:
{
_id: null,
id_test: { $push: "$id_test" }
}
},
{ $project: { final:{ $setDifference: [ arrayIds , "$id_test" ] }, _id: 0 } }
]
);
const final = players.final // [43, 555]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.