Skip to content

Instantly share code, notes, and snippets.

@romainnorberg
Created March 30, 2020 19:26
Show Gist options
  • Save romainnorberg/e5712773029b21c5673cfc55070766e7 to your computer and use it in GitHub Desktop.
Save romainnorberg/e5712773029b21c5673cfc55070766e7 to your computer and use it in GitHub Desktop.

count & sort by subdocuments

db.Visitor.aggregate([
    {
        $project: {
            "n": { $size: "$history" }
        }
    }
    ,
    {
        $group: {
            "_id": "$_id",
            "alln": { $sum: "$n" }
        }
    },
    {
        $sort: { "alln": -1 }

    }
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment