简体   繁体   English

如何查询mongodb中的子文档?

[英]How to query sub documents in mongodb?

how to query sub documents in mongodb, i would like to get all sub document with the titles of book equal to cars only如何查询mongodb中的子文档,我想获取所有书名等于汽车的子文档

here is the document below i would like to query这是下面我想查询的文件

[
  {
      "_id": "5e7148313ecba10bdc04d0b3",
      "name": "crystal",
      "author": "barbra",
      "titles": [
          {
              "_id": "5e7bbc9898959e1c1c694d12",
              "book": "cars",
          },
          {
              "_id": "5e86bcbef5ef401554058e48",
              "book": "buses",
             },
          {
              "_id": "5e8a5107ea148f1c588534e5",
              "book": "cars",
          }
      ]
  }
]

this is the query i tried below to get the sub documents, it did not work这是我在下面尝试获取子文档的查询,它没有用

.aggregate([
  { $match: { "name": 'crystal', } },
  {
    $project: {
      "titles": 1, _id: 0, 
      "titles": { $match: { "$book": 'cars', } }
    }
  },
])
.aggregate([
  { 
    $match: { 
      "name": 'crystal',  
      titles: { $elemMatch: { "book": "cars"} }
   }
  },
  {
    $project: {
       _id: 0,
      titles: 1
    }
  }
])

use $elemMatch operator to search in array of objects and remove the $ sign you added to book.使用$elemMatch运算符在对象数组中搜索并删除您添加到 book 的 $ 符号。 this should work for you这应该适合你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM