12

给定这样的集合:..

[
  {
    "_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但不显示嵌套文档本身。

4

3 回答 3

27

使用点符号

当字段包含嵌入文档时,查询可以指定嵌入文档的完全匹配,也可以使用点表示法指定嵌入文档中各个字段的匹配。

db.coll.find({
   "accounts._id" :ObjectId("5546329a470019850084a611")
})

如果您只需要输出数组中包含 _id 的部分,则需要在投影中使用美元

位置 $ 运算符将查询结果中的 an 内容限制为仅包含与查询文档匹配的第一个元素。

您的查询将如下所示:

db.coll.find({
   "accounts._id" :ObjectId("5546329a470019850084a611")
}, {
   "accounts.$.": 1
})

PS如果您需要修改后问题中的输出,请使用:

db.coll.find({
   "accounts._id" :ObjectId("5546329a470019850084a611")
 }, {
   accounts : 0
 })
于 2015-05-05T05:25:15.300 回答
6

$elemMatch 运算符将查询结果中的字段内容限制为仅包含与 $elemMatch 条件匹配的第一个元素。

在你的情况下:

db.users.find({'_id': ObjectId('5546329a470000850084a621')}, {accounts: {$elemMatch: {_id: ObjectId('5546329a470000850084a655')}}})

参考:Mongo Docs

于 2015-05-05T05:33:42.737 回答
1

$elemMatch在标准中使用并在项目中使用位置$运算符,如下所示:

db.users.find({
  "accounts": {
    "$elemMatch": {
      "_id": ObjectId("5546329a470019850084a611"),
      "default": true
    }
  }
}, {
  "accounts.$._id": 1 // "accounts.$": 1 also works
}).pretty()
于 2015-05-05T05:27:12.683 回答