0

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.

1 Answer 1

2

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" } ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.