MongoDB:如何通过嵌套文档中的ID查找文档 [英] MongoDB: How to find a document by an id inside a nested document
本文介绍了MongoDB:如何通过嵌套文档中的ID查找文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出这样的集合:..
Given a collection like this:..
[
{
"_id" : ObjectId("5546329a470000850084a621"),
"name": "Joe",
"surname": "Smith",
"accounts": [
{
"_id" : ObjectId("5546329a470000850084a655"),
"default": true,
"status" : "approved",
"activationTime" : ISODate("2013-05-03T14:37:15.025Z")
},
{
"_id" : ObjectId("5546329a470000850084a688"),
"default": true,
"status" : "approved",
"activationTime" : ISODate("2014-06-03T14:37:15.025Z")
}
]
},
{
"_id" : ObjectId("9546329a470079850084a622"),
"name": "Jimmy",
"surname": "Brown",
"accounts": [
{
"_id" : ObjectId("5546329a470790850084a651"),
"default": true,
"status" : "suspended",
"activationTime" : ISODate("2015-02-03T14:37:15.025Z")
},
{
"_id" : ObjectId("5546329a470019850084a611"),
"default": true,
"status" : "approved",
"activationTime" : ISODate("2015-04-03T14:37:15.025Z")
}
]
},
]
...如何通过accounts.N._id
查找文档?我已经尝试过了...
... how do I find a document by accounts.N._id
? I've tried this...
db.users.find(
{},
{
"accounts": 0, "accounts": {
"$elemMatch": { "_id" : ObjectId("5546329a470019850084a611"), "default": true }
}
}
)
...但是它不起作用,因为我只得到所有文档的_id
:
... but it does't work since I get only the _id
of all the documents:
{ "_id" : ObjectId("5546329a470000850084a621") }
{ "_id" : ObjectId("9546329a470079850084a622") }
我想念什么吗?
编辑
我实际需要的结果是这样的:
The result that I actually need is something like this:
{
"_id" : ObjectId("9546329a470079850084a622"),
"name": "Jimmy",
"surname": "Brown"
}
例如,我需要按accounts.N._id
查找,但不显示嵌套文档本身.
For instance, I need to find by accounts.N._id
but without showing the nested document itself.
推荐答案
查看全文