gpt4 book ai didi

node.js - Mongodb 查询过滤文档中对象的嵌套数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:40 27 4
gpt4 key购买 nike

我有以下文档

{
"userid": "5a88389c9108bf1c48a1a6a7",
"email": "abc@gmail.com",
"lastName": "abc",
"firstName": "xyz",
"__v": 0,
"friends": [{
"userid": "5a88398b9108bf1c48a1a6a9",
"ftype": "SR",
"status": "ACCEPT",
"_id": ObjectId("5a9585b401ef0033cc8850c7")
},
{
"userid": "5a88398b9108bf1c48a1a6a91111",
"ftype": "SR",
"status": "ACCEPT",
"_id": ObjectId("5a9585b401ef0033cc8850c71111")
},
{
"userid": "5a8ae0a20df6c13dd81256e0",
"ftype": "SR",
"status": "pending",
"_id": ObjectId("5a9641fbbc9ef809b0f7cb4e")
}]
},
{
"userid": "5a88398b9108bf1c48a1a6a9",
"friends": [{ }],
"lastName": "123",
"firstName": "xyz",
.......
},
{
"userid": "5a88398b9108bf1c48a1a6a91111",
"friends": [{ }],
"lastName": "456",
"firstName": "xyz",
...
}
  • 第一个查询

这里我想从friends数组中获取userId,其状态等于“ACCEPT”。即

 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 
  • 第二个查询

之后,我必须对同一个集合进行另一个查询,以获取第一个查询中返回的每个用户 ID 的详细信息。 最终查询将返回 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 的详细信息 两个用户 ID 即

[
{
userid" : "5a88398b9108bf1c48a1a6a9",
"lastName" : "123",
"firstName" : "xyz"
},
{
"userid" : "5a88398b9108bf1c48a1a6a91111",
"lastName" : "456",
"firstName" : "xyz"
}
]

到目前为止我已经尝试过

 Users.find ({'_id':5a88389c9108bf1c48a1a6a7,"friends.status":'ACCEPT'}, (error, users) => {})  
or


Users.find ({'_id':5a88389c9108bf1c48a1a6a7, friends: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => {})

最佳答案

使用聚合框架的 $map $filter 运算符(operator)来处理任务。 <强> $filter 将根据指定条件过滤好友数组,即状态应等于 "ACCESS" $map 会将结果从过滤后的数组转换为所需的格式。

对于第二个查询,附加 $lookup 管道步骤,对用户集合进行自连接,以检索与前一个管道中的 id 匹配的文档。

运行以下聚合操作将生成所需的数组:

User.aggregate([
{ "$match": { "friends.status": "ACCEPT" } },
{ "$project": {
"users": {
"$map": {
"input": {
"$filter": {
"input": "$friends",
"as": "el",
"cond": { "$eq": ["$$el.status", "ACCEPT"] }
}
},
"as": "item",
"in": "$$item.userid"
}
}
} },
{ "$lookup": {
"from": "users",
"as": "users",
"localField": "users",
"foreignField": "userid"
} },
]).exec((err, results) => {
if (err) throw err;
console.log(results[0].users);
});

关于node.js - Mongodb 查询过滤文档中对象的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com