Search code examples
arraysmongodbprojection

How to projection element in multi array field of MongoDb collection?


Is there a way to get only specific field values ​​from a multi array?

db.test.insert({'id':'stack', 'nums':[{'name':'Dave', 'num': 1, 'phones' :[{'id':1, 'number':'000-000'}, {'id':2, 'number':'000-001'}]}]})
{
    "_id" : "63b3896a5b5d9de96b6277fa",
    "id" : "stack",
    "nums" : [
        {
            "name" : "Dave",
            "num" : 1,
            "phones" : [
                {
                    "id" : 1,
                    "number" : 0
                },
                {
                    "id" : 2,
                    "number" : -1
                }
            ]
        }
    ]
}

the answer i want

{'id':1, 'number':'000-000'}

I want to print only the value with 'id' 1 in 'phones'.


Solution

  • db.collection.aggregate([
      {
        "$unwind": "$nums"
      },
      {
        $project: {
          "phones": {
            $filter: {
              input: "$nums.phones",
              cond: {$eq: ["$$this.id",1]
              }
            }
          }
        }
      }
    ])
    

    Playground