MongoDB: How to find a document by an id inside a nested document

落花浮王杯 提交于 2019-12-03 06:44:39

Use 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")
})

If you need to output only the part of an array where you have your _id you need to use 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.

and your query would look like:

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

P.S. if you need the output like in your modified questions, use this:

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

The $elemMatch operator limits the contents of an field from the query results to contain only the first element matching the $elemMatch condition.

In your case:

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

Refer: Mongo Docs

Use $elemMatch in criteria and use $ positional operator in project as below :

db.users.find({
  "accounts": {
    "$elemMatch": {
      "_id": ObjectId("5546329a470019850084a611"),
      "default": true
    }
  }
}, {
  "accounts.$._id": 1 // "accounts.$": 1 also works
}).pretty()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!