0

I have a search result stored in a Mongo collection in the following format. This is one document.

{
 "result": [
    {
      "provider_id": 1,
      "code" :1,
      "comm_id" : 1 
        },

    {
      "provider_id": 1,
      "code" :2,
      "comm_id" : 2 
        },
    {
      "provider_id": 2,
      "code" :"A",
      "comm_id" : 1 
        },

    {
      "provider_id": 1,
      "code" :"B",
      "comm_id" : 3 
        }
     ]
}

How can I write a query and apply a filter like {"result.comm_id":1} so that the result set has

 {
"result":[
    {
      "provider_id": 1,
      "code" :1,
      "comm_id" : 1 
        },

    {
      "provider_id": 2,
      "code" :"A",
      "comm_id" : 1 
        }

     ]
     }   
Jayadevan
  • 1,306
  • 2
  • 12
  • 33
  • Possible duplicate of [How to filter array in subdocument with MongoDB](https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb) – Himanshu Sharma Aug 28 '19 at 12:32

1 Answers1

2

Use aggregate pipeline as below using $filter

db.collection.aggregate([
  {
    $project: {
      result: {
        $filter: {
          input: "$result",
          as: "item",
          cond: {
            $eq: [
              "$$item.comm_id",
              1
            ]
          }
        }
      }
    }
  }
])
sushant mehta
  • 1,244
  • 1
  • 7
  • 13