user1198485
user1198485

Reputation:

Retrieve Array Of Documents in MongoDB

I have a MongoDB Document like as follows

{
"_id":1,
"name":"XYZ"

ExamScores:[
{ExamName:"Maths", UnitTest:1, Score:100},
{ExamName:"Maths", UnitTest:2, Score:80},
{ExamName:"Science", UnitTest:1, Score:90}
]
}

I Need to retrieve this document so that it has to show only Maths Array. Like as follows

{
    "_id":1,
    "name":"XYZ"

    ExamScores:[
    {ExamName:"Maths", UnitTest:1, Score:100},
    {ExamName:"Maths", UnitTest:2, Score:80},        
    ]
    }

How Can I Do That ?

Upvotes: 0

Views: 126

Answers (2)

Sammaye
Sammaye

Reputation: 43884

As @karin states there is no, normal, in query method of doing this.

In version 2.2 you can use $elemMatch to project the first matching result from ExamScores but you cannot get multiple.

That being said, the aggregation framework can do this:

db.col.aggregate([
    {$unwind: '$ExamScores'},
    {$match: {'ExamScores.ExamName':"Maths"}},
    {$group: {_id: '$_id', name: '$name', ExamScores: {$push: '$ExamScores'}}}
])

Something like that anyway.

Upvotes: 2

Karin Stein
Karin Stein

Reputation: 11

This has been asked before MongoDB query to limit values based on condition, the only answer there says it is not possible, but that there is a request to implement that.

Upvotes: 0

Related Questions