[英]find whether individual array element exists in the mongodb document's array
有沒有辦法找到單個元素是否存在於 mongodb 文檔的數組中。
例如:如果我有一個文件
{
"_id": "A",
"userId": "B",
"selectedUsers": ["C", "D"]
}
我還有另一個數組 ["E", "C"]。
我想編寫一個查詢,當向它提供 userId 和上述數組時,該查詢給出的結果為 [false, true],因為“E”不在 selectedUsers 數組中,而“C”在 selectedUsers 數組中。
我知道我可以先找到具有給定 userId 的文檔,然后對它的單個元素使用 Array.find() 。 但我想知道在 mongodb 查詢中是否有辦法做到這一點。
另外,我正在使用 nodeJS 和貓鼬。
為了清楚起見,我需要使用 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;
你可以只使用$in
db.collection.find({selectedUsers: {$in: ["E", "C"]}})
這樣的事情怎么樣?
var input = ['E', 'C'];
db.collection.aggregate(
[
{
$match: {
_id: 'A'
}
},
{
$unwind: '$selectedUsers'
},
{
$set: {
has: { $in: ['$selectedUsers', input] }
}
},
{
$group: {
_id: null,
result: { $push: '$has' }
}
},
{
$project: {
_id: 0
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.