0

I have a collection of item that has price depending on user membership (silver, gold, platinum)

{ 
  ..
  memberships: [
   {level: "silver", price: 100},
   {level: "gold", price: 90},
   {level: "platinum", price: 80}
  ]
}

when silver users browse for items, they will need to see items sorted by price using memberships price where level is silver.

How do I sort this ?

1

1 Answer 1

1

You can use $unwind and then $sort in aggregation pipeline. eg: here

db.collection.aggregate(
{ $unwind: "$memberships" },
{ $sort: { "memberships.price": 1 }},
{ $group: {
    _id: "$_id",
    "memberships": { $push: "$memberships" }
  }
})
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.