Utsav Upadhyay
Utsav Upadhyay

Reputation: 475

MongoDB: How to find specific value in nested array, if found then show only that array not all?

[![enter image description here][1]][1]

I am trying to find id "D0182" in client_id array if found then only it will show the client_id document, but it is showing me the whole document.

Here is my query -

db.getCollection('news').find({"newsSources.client_id":"343a","date": "2021-01-22"}, {"_id":0,"newsSources.title" :1, "newsSources.client_id":1})

Upvotes: 2

Views: 801

Answers (1)

varman
varman

Reputation: 8894

You can use aggregation to filter out objects from array.

db.collection.aggregate([
  {
    "$addFields": {
      "newsSources": {
        $filter: {
          input: "$newsSources",
          cond: {
            $in: [
              "D0108",
              "$$this.clientId"
            ]
          }
        }
      }
    }
  }
])

Working Mongo playground

Upvotes: 2

Related Questions