给定一个这样的集合:..
[
{
"_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
查找文档?我已经尝试过这个...
db.users.find(
{},
{
"accounts": 0, "accounts": {
"$elemMatch": { "_id" : ObjectId("5546329a470019850084a611"), "default": true }
}
}
)
...但它不起作用,因为我只得到所有文档的 _id
:
{ "_id" : ObjectId("5546329a470000850084a621") }
{ "_id" : ObjectId("9546329a470079850084a622") }
我错过了什么吗?
编辑
我实际需要的结果是这样的:
{
"_id" : ObjectId("9546329a470079850084a622"),
"name": "Jimmy",
"surname": "Brown"
}
例如,我需要通过 accounts.N._id
查找,但不显示嵌套文档本身。
最佳答案
使用dot notation :
When the field holds an embedded document, a query can either specify an exact match on the embedded document or specify a match by individual fields in the embedded document using the dot notation.
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
})
如果您需要仅输出数组中包含 _id 的部分,则需要使用 dollar in projection
The positional $ operator limits the contents of an from the query results to contain only the first element matching the query document.
您的查询将如下所示:
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
}, {
"accounts.$.": 1
})
P.S.如果您需要像修改后的问题中那样的输出,请使用以下内容:
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
}, {
accounts : 0
})
关于MongoDB:如何通过嵌套文档中的 id 查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044792/