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
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.
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.
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)
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 } }
] )
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With