Mongodb aggregation pipeline how to limit a group push

前端 未结 2 460
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 18:10

I am not able to limit the amount of pushed elements in a group function with aggregation pipeline. Is this possible? Small example:

Data:



        
2条回答
  •  感动是毒
    2020-12-01 18:46

    Suppose the bottom left coordinates and the upper right coordinates are respectively [0, 0] and [100, 100]. From MongoDB 3.2 you can use the $slice operator to return a subset of an array which is what you want.

    db.collection.aggregate([
        { "$match": { 
            "loc": { 
                "$geoWithin":  { 
                    "$box": [ 
                        [0, 0], 
                        [100, 100]
                    ]
                }
            }}
        }},
        { "$group": { 
            "_id": "$name",
            "submitted": { "$max": "$submitted" }, 
            "preview": { "$first": "$preview" }
            "locs": { "$push": "$loc" }
        }}, 
        { "$project": { 
            "locs": { "$slice": [ "$locs", 5 ] },
            "preview": 1,
            "submitted": 1
        }},
        { "$limit": 10 }
    ])
    

提交回复
热议问题