有没有办法找出单个元素是否存在于 mongodb 文档的数组中。
例如:
如果我有文件
{
"_id": "A",
"userId": "B",
"selectedUsers": ["C", "D"]
}
我有另一个数组作为[“E”,“C”]。我想编写一个查询,当 userId 和上面的数组被提供给它时,结果为 [false, true],因为“E”不在 selectedUsers 数组中,而“C”在 selectedUsers 数组中。
我知道我可以先找到具有给定 userId 的文档,然后在其上对单个元素使用 Array.find()。但我想知道在 mongodb 查询中是否有办法做到这一点。
另外,我正在使用 nodeJS 和 Mongoose 。
为了清楚起见,我需要使用 mongodb 查询获得与以下 js 代码相同的功能。
// req is the http request
// Selected is the mongoose Model for above document
// usersToCheck = ["E", "C"] (this is the second array)
const result = Selected.findOne({ userId: req.userId});
const { selectedUsers } = result;
const response = usersToCheck.map(uid => {
if(selectedUsers.some(id => id === uid)){
return true;
}
return false;
})
// response = [false, true]
现在,假设 usersToCheck 和 selectedUsers 的大小为 n,上述代码的复杂度为 O(n^2)。
我想知道如何使用 mongodb 查询获得与上述相同的响应。因此,我可以根据 selectedUsers 数组索引集合并缩短获得响应所需的时间。
或者,任何其他改进上述代码的方法都值得赞赏。
在此先感谢您的帮助。
最佳答案
试试这个:
const result = Selected.aggregate([
{
$match: {
userId: req.userId
}
},
{
$project: {
_id: 0,
result: {
$map: {
input: ["E", "C"],
in: {
$in: [
"$$this",
"$selectedUsers"
]
}
}
}
}
}
]).exec();
const response = result[0].result;
MongoPlayground
关于javascript - 查找单个数组元素是否存在于 mongodb 文档的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649947/