Haotian Chyi
Haotian Chyi

Reputation: 75

Get the elements that satisfy the criteria from the array in the document from MongoDB collection?

If I have some documents in a collection like these:

db.test.find()
[{
    author_id: 1
    reviews: [{article_id: 1, score: 10, ...},
              {article_id: 2, score: 7, ...},
              {article_id: 3, score_9, ...}
              ...
             ]
},
{
    author_id: 2
    reviews: [{article_id: 2, score: 8, ...},
              {article_id:4, score: 3, ...}
              ...
             ]
},
...
]

How can I get a list which contains all reviews satisfy the criteria, eg. article_id equels to 2, just like:

[{article_id: 2, author_id: 1, score: 7},
{article_id: 2, author_id: 2, score: 8}
...
]

I'm newer in MongoDB ^_^.

Upvotes: 0

Views: 56

Answers (1)

s7vr
s7vr

Reputation: 75914

You can use below aggregation in mongo version 3.6.

$filter with $arrayElemAt to output the matching review followed by $mergeObjects to combine the matching review doc with author_id.

$replaceRoot to promote the merged document to top level.

db.col.aggregate({
  "$replaceRoot":{
    "newRoot":{
      "$mergeObjects":[
        {"author_id":"$author_id"},
        {"$arrayElemAt":[
          {"$filter":{
            "input":"$reviews",
            "as":"rv",
            "cond":{"$eq":["$$rv.article_id",2]}
          }},
        0]}
      ]
    }
  }
})

Upvotes: 1

Related Questions