user3491125
user3491125

Reputation: 376

How to sort by array of values in mongodb

I have a Mongodb collection containing products with a size and i would like to sort them in a certain order.

In SQL you would do SORT BY FIELD(size, 'XS', 'S', 'M', 'L') but I have strictly no idea how to achieve such operation with mongodb.

Upvotes: 0

Views: 34

Answers (1)

user912321312
user912321312

Reputation: 36

Unfortunately the sort(for queries)/orderBy(for aggregations) follows the syntax:

<field1>: <sort order>;

So, you cannot replicate the same behaviour as in SQL. The solution for you would probably be to pass the orderBy/sort in filters, query again on those results.

Another solution would be to use aggregations, but you have to specify which fields from products you want to have in the final result:

db.products.aggregate( [ { $group : { _id : "$size", products: { $push: "$name" } } } ] )

Response will look like this:

{ "_id" : "L", "products" : [ ] } { "_id" : "M", "products" : [ "a", "b" ] }

Another aggregation example which first filters products then groups them:

 db.products.aggregate([   
   { $match: { size: { $in: ["M", "L"] } } },   
   { $group: { _id: "$size", products: { $push: {name: "$name", size:"$size"} } } }
 ]);

// { "_id" : "M", "products" : [ { "name" : "a2", "size" : "M" } ] }
// { "_id" : "L", "products" : [ { "name" : "a1", "size" : "L" }, { "name" : "a3", "size" : "L" } ] }

Upvotes: 2

Related Questions