Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 900
ben lemasurier Avatar asked Sep 30 '11 17:09

ben lemasurier


People also ask

How do I sort values in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

How do I sort an array in MongoDB aggregation?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

How sort works in MongoDB?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field. When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest: MinKey (internal type)


2 Answers

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 } }
] )
like image 59
drogon Avatar answered Nov 16 '22 02:11

drogon


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})
like image 32
kamaradclimber Avatar answered Nov 16 '22 03:11

kamaradclimber