Search code examples
arraysmongodbmongoosemongodb-querypymongo

How to use mongodb projection query in array elements


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

Solution

  • 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