Home > Back-end >  How to use mongodb projection query in array elements
How to use mongodb projection query in array elements

Time:04-02

I would like to project only "type":"A" in menu. is there a way to achieve this?

    "_id" : "1",
    "menu" : [ 
        {
            "type" : "A",
            "items" : [ 
                {
                    "key" : "Add",
                    "enabled" : true,
                }            ]
        }, 
        {
            "type" : "B",
            "items" : [ 
                {
                    "key" : "Add",
                    "enabled" : true,
                }    ]
        }
    ]
}

CodePudding user response:

If you want tou output only the menu which type is A you can use $elemMatch in a find query (take care because this only return the first matched element)

db.collection.find({},
{
  "menu": {
    "$elemMatch": {
      "type": "A"
    }
  }
})

Example here

Or $filter in an aggregate query (this returns all objects with type: "A" in the array):

db.collection.aggregate([
  {
    "$project": {
      "menu": {
        "$filter": {
          "input": "$menu",
          "cond": {
            "$eq": [
              "$$this.type",
              "A"
            ]
          }
        }
      }
    }
  }
])

Example here

  • Related