manny
manny

Reputation: 415

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

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', } }
    }
  },
])

Upvotes: 1

Views: 53

Answers (1)

Emmanuel Ani
Emmanuel Ani

Reputation: 462

.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. this should work for you

Upvotes: 1

Related Questions