简体   繁体   中英

Limiting number of different kind of results in mongoDB aggregation

I would like to write an aggregation that take the following documents:

{ type: "dog", name: "Charlie" }
{ type: "dog", name: "Felix" }
{ type: "dog", name: "John" }
{ type: "cat", name: "Tum" }

And returns up to 2 of each kind, not grouped in any separate way:

{ type: "dog", name: "Charlie" }
{ type: "dog", name: "Felix" }
{ type: "cat", name: "Tum" }

Meaning just up to two cats plus up to two dogs. Does grouping and limiting the way to go here? If so - how?

You can group the documents by type , create a list of the names per group, $project the list to only have two elements with $slice and then flatten the list using $unwind , something like the following:

Model.aggregate([
    { "$group": {
        "_id": "$type",
        "data": { "$push": "$name" }
    } },
    { "$project": {
        "type": "$_id",
        "name": { "$slice": ["$data", 2] }
    } },
    { "$unwind": "$name" }
]).exec(callback);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM