MongoDB sort by count

I have a document that looks something like this:

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

Can I sort by the number of "ratings"? Doing something like:

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

causes an error:

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

+8
sorting mongodb
source share
2 answers

This is not possible directly with mongodb [ 1 ]

One solution, if you often use this query, is to increase and decrease the number of "counters" each time you change the grades array and sort in this field.

The document will look like this:

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

and you request using

 db.comments.find().sort({count: -1}) 
+8
source share

There is already a noticeable answer, but I thought I would add that this can be done using the aggregation structure:

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

All Articles