MongoDB:如何通过嵌套文档中的 id 查找文档

标签 mongodb mongodb-query embedded-documents

给定一个这样的集合:..

[
  {
    "_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/

相关文章:

java - 泛型是处理多个数据库的答案吗?

mongodb - 查询mongodb中嵌入文档的数组

javascript - MongoDB 投影将子对象作为列返回

MongoDB:自动捕获数据库(而不是应用程序)中的创建/更新时间

MongoDB 聚合 - $unwind 顺序文档是否与嵌套数组顺序相同

mongodb - mongoDB 中的 Group by 与属性构造

node.js - MongoDB 从文本搜索中排除精确匹配

arrays - 如何查询 MongoDB 数组中的单个嵌入文档?

php - 变更集 Doctrine 事件监听器中的嵌入式文档

mongodb - MongoDB Hadoop PIG脚本引发 “Undefined Parameter :gte”异常