javascript - Mongodb IN和返回元素不匹配
问题描述
我有一个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 数组id_test
:
const arrayIds = [ 132, 43, 90, 555];
然后我想获取数组中不匹配的元素(不在 $nin 的集合中)。我的例子我需要输出:[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]
推荐阅读
- swift - 如何在 Swift / Codable 中解码日期?
- jquery - reactjs状态变化时如何正确更新jquery数据表内容?
- java - org.springframework.beans.factory.BeanCreationException:创建工厂bean时出错
- solidity - Metamask 自定义 RPC 未发送正确的合约信息
- android - Android - 毕加索获取图像高度
- python - 如何更改网页代码打开的目录TCP服务器python
- html - 如何使 firstChild 高度为 100% flexbox 包装项目
- firebase - Firebase 不会更新我对自定义域的更改
- mongodb - Mongodb Compass和shell中的mongodb查找聚合结果不同
- r - Taking values from data table rows and putting it in a cell as a list in R