2

[![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})

4
  • Can you post the document as a code snippet instead of image! Commented Jan 22, 2021 at 13:20
  • And Id know that the client_id is inside the newsSources. Do you need to filter only the object inside the array or you need to get all documents which has the client_id in your collection? Commented Jan 22, 2021 at 13:23
  • as you can see in the image above client_id: ["W0086"] is also displayed, I am trying to show only that [client_id] array which has the value ["D0182"] , if not then it should hide not displayed Commented Jan 22, 2021 at 13:30
  • @varman I am using MongoDB shell only. Commented Jan 22, 2021 at 13:31

1 Answer 1

2

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

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.