当前位置: 动力学知识库 > 问答 > 编程问答 >

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?

网友答案:

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" }
            }
        }
    ])
分享给朋友:
您可能感兴趣的文章:
随机阅读: