Home > other >  How to get single field in mongodb query?
How to get single field in mongodb query?

Time:12-15

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.

CodePudding user response:

  • $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

CodePudding user response:

you can make like this

db.collection.aggregate([
  {
    "$match": {
      $and: [
        {
          "book": "Flash3"
        },
        {
          "chapters.chap_no": "2"
        },
        {
          "chapters.sub_chapter.sub_no": "1"
        }
      ]
    }
  },
  {
    "$unwind": "$chapters"
  },
  {
    "$unwind": "$chapters.sub_chapter"
  },
  {
    "$match": {
      $and: [
        {
          "book": "Flash3"
        },
        {
          "chapters.chap_no": "2"
        },
        {
          "chapters.sub_chapter.sub_no": "1"
        }
      ]
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$chapters.sub_chapter"
    }
  }
])
  • Related