【发布时间】:2018-08-08 10:18:12
【问题描述】:
我有以下文件
{
"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",
...
}
- 第一个查询
这里我想从好友数组中获取用户 ID,它的状态等于“接受”。 即
[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) => {})
【问题讨论】:
-
AlejandroMontilla :我尝试使用以下 mongooes Query 从集合中获取数据
Users.find ({'userid':5a88389c9108bf1c48a1a6a7, friends: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => { }); -
请将
find添加到您的问题中。那find恢复指定的文档? -
您缺少
ObjectId("5a88389c9108bf1c48a1a6a7")=>Users.find({ _id:ObjectId("5a88389c9108bf1c48a1a6a7" )})。也看看$redact -
能否请edit 向我们展示您预期的最终输出?
-
@chridam :非常感谢您为第一个查询所做的努力。它对我来说很好。我想要来自同一文档的所有用户(即 firstQuery 结果)的详细信息。希望你能理解我的查询,谢谢:)
标签: node.js mongodb mongoose mongodb-query aggregation-framework