给定这样的集合:
[
{
"_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
但不显示嵌套文档本身。
使用点符号:
当字段包含嵌入式文档时,查询可以指定嵌入式文档上的完全匹配,也可以使用点符号指定嵌入式文档中各个字段的匹配。
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
})
如果只需要输出具有_id的数组部分,则需要在投影中使用dollar
位置$运算符将查询结果中的内容限制为仅包含与查询文档匹配的第一个元素。
您的查询将类似于:
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
}, {
"accounts.$.": 1
})
PS,如果您需要修改后的问题中的输出,请使用以下命令:
db.coll.find({
"accounts._id" :ObjectId("5546329a470019850084a611")
}, {
accounts : 0
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句