ben lemasurier
ben lemasurier

Reputation: 2592

MongoDB sort by subdocument count

I have a document which looks something like:

{
        "_id" : ObjectId("4e84f78b26d2046d5d00b5b2"),
        "parent_id" : 0,
        "ratings" : [
                "20716",
                "78167"
        ],
        "text" : "test"
}

Is it possible to sort by the count of "ratings"? Doing something like:

db.comments.find().sort({rating.count(): -1})

throws an error:

SyntaxError: missing : after property id (shell):0

Upvotes: 9

Views: 5262

Answers (2)

drogon
drogon

Reputation: 1825

There is a marked answer already, but I thought I'd add that this can be done using the aggregation framework:

db.comments.aggregate( [
   { $unwind: "$ratings" },
   { $group : { _id : { parent_id: "$parent_id", text: "$text"  }, 
                ratingsCount : { $sum : 1 } } },
   { $sort : { ratingsCount : -1 } }
] )

Upvotes: 18

kamaradclimber
kamaradclimber

Reputation: 2489

That's not directly possible with mongodb [1]

One solution, if you frequently use this query, is to increment and decrement a field 'count' each time you modify the ratings array and sort on that field.

You document will look like :

{
    "_id" : ObjectId("4e84f78b26d2046d5d00b5b2"),
    "parent_id" : 0,
    "ratings" : [
            "20716",
            "78167"
    ],
    count : 2
    "text" : "test"
}

and you query with

db.comments.find().sort({count: -1})

Upvotes: 8

Related Questions