Skip to content
Advertisement

How to get single field in mongodb query?

I have data like this:

{ id : 1, 
    book: "Flash", 
    chapters: [
        { 
      chap_no: "1", 
      sub_chapter: [
                {sub_no: 1, description: "<description>"
                },
                {sub_no: 2, description: "<description>"
                },
            ]
        }
    ]
}

i want to show one field like this base on book -> chapter_no -> sub_no

{
 sub_no: 2, description: "<description>"
}

in mongodb query.

Advertisement

Answer

  • $match
  • $unwind
  • $unwind
  • $match
  • $replaceRoot
db.collection.aggregate([
  {
    "$match": {
      "chapters.sub_chapter.sub_no": 2
    }
  },
  {
    "$unwind": "$chapters"
  },
  {
    "$unwind": "$chapters.sub_chapter"
  },
  {
    "$match": {
      "chapters.sub_chapter.sub_no": 2
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$chapters.sub_chapter"
    }
  }
])

mongoplayground

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement