2

I have MongoDB document like below: is there a query to Sort the documents with the length of subscribedGroups? which can be ascending or descending.

{ 
    "_id" : ObjectId("58c29d9ec79d585c0e16b110"), 
    "subscribedGroups" : [
      ObjectId("5b28a9190c8c0d0014b03a0c"), 
      ObjectId("5b2930650b813a0014a3294d"), 
      ObjectId("5b29f1b5243d470014d6d351")
    ]
}
1
  • Do you have an example of what you've tried so far? Commented Jun 20, 2018 at 7:22

1 Answer 1

6

You can find the size of the subscribedGroups using $size and then easily $sort with the length of the array

db.collection.aggregate([
  {
    $addFields: {
      subscribedGroupsLength: {
        $size: "$subscribedGroups"
      }
    }
  },
  {
    $sort: {
      subscribedGroupsLength: -1
    }
  }
])

See the sample

Sign up to request clarification or add additional context in comments.

1 Comment

this is by far better than using old unwind, group, and then sort idea!

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.