0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.