user1504992
user1504992

Reputation: 525

Combining $elemMatch and $ in mongodb projection

I have the following documents in my MongoDB collection:

{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }
{ "_id" : 2, "semester" : 2, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }

I would like to retrieve all the documents that match the 1st semester and present for each of them the id field, semester field and the first grade that is larger than 80. I.e., for the documents above, the result of the query should be:

{ "_id" : 1, "semester" : 1, "grades" : 87 }
{ "_id" : 3, "semester" : 1, "grades" : 85 }

Is this possible? What is the query that does this (I'm using MongoDB 2.6) ? I know how to present all the grades that are larger than 80, using $elemMatch for projection, or how to present just the 1st grade, using the '$' operator, but how do I combine them to choose the 1st one of them?

Upvotes: 2

Views: 536

Answers (1)

Sede
Sede

Reputation: 61273

You can use aggregation pipeline

  • $unwind the grades array
  • $first to return the first value greater than 80
    db.collection.aggregate([
        { "$unwind": "$grades" }, 
        { "$match": 
            {
                "semester": 1, 
                "grades": { "$gt": 80 }
            }
        }, 
        { "$group": 
            { 
                "_id": "$_id", 
                "semester": { "$first": "$semester" }, 
                "grades": { "$first": "$grades" }
            }
        }
    ])

Upvotes: 2

Related Questions