Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

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

enter image description here

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":"A0003","date": "2021-01-22"}, {"_id":0,"newsSources.title" :1, "newsSources.client_id":1})

question from:https://stackoverflow.com/questions/65845495/mongodb-how-to-find-specific-value-in-nested-array-if-found-then-show-only-tha

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...