[英]Mongodb IN and return elements not matched
我有一個這樣的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"
}
我有一個帶有id_test
的 ID 數組:
const arrayIds = [ 132, 43, 90, 555];
然后我想獲取數組中不匹配的元素(不在 $nin 的集合中)。 我的例子我需要 output: [43, 555]
像這樣:(但我想知道是否可以通過一個查詢):
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]
是的,您可以通過聚合在單個查詢中執行此操作,
首先,我們搜索玩家,然后創建他們的 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.