1

This is my data:

{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 2
},
{
   "name": "some name",
   "blockNumber": 9,
   "uniqueId: 3
},
{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 1
},

This is my query:

myModel.aggregate([
        {
          $match: someFilter,
        },
        {
          $sort: { blockNumber: -1 },
        },
])

And there is the expected result:

{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 1
},
{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 2
},
{
   "name": "some name",
   "blockNumber": 9,
   "uniqueId: 3
}

I am looking for a way to additionally sort the data depending on a second value (in this case uniqueId) only if blockNum is the same for multiple documents, so that the final result is also sorted by descending uniqueId. Example:

{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 2
},
{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId: 1
},
{
   "name": "some name",
   "blockNumber": 9,
   "uniqueId: 3
}
    
4
  • 1
    The final result is incorrect. You mentioned sort by blockNumber descending and uniqueId ascending, the document with blockNumber: 10 and uniqueId: 1 will come first then followed by blockNumber: 10 and uniqueId: 2. Commented Aug 15, 2022 at 10:07
  • you can add more than one field to $sort stage check this Commented Aug 15, 2022 at 10:10
  • @1sina1 If I add another sort stage the final result will be sorted by uniqueId files, or I am wrong? Commented Aug 15, 2022 at 10:19
  • 1
    docs. if you use two sort stage it will get sort by the last one. if you use multiple fields on one $sort documents are first sorted by <field1>. Then documents with the same <field1> values are further sorted by <field2>. Commented Aug 15, 2022 at 10:27

2 Answers 2

2

I actually figured it out: just add a second field to the sort stage. The query is:

myModel.aggregate([
        {
          $match: someFilter,
        },
        {
          $sort: { blockNumber: -1, uniqueId: -1 },
        },
])

The result:

{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId": 2
},
{
   "name": "some name",
   "blockNumber": 10,
   "uniqueId": 1
},
{
   "name": "some name",
   "blockNumber": 9,
   "uniqueId": 3
}
Sign up to request clarification or add additional context in comments.

1 Comment

would you mind, providing an example in your response? That way anyone googling this, has an example on how to do it
-3

Try this:

.sort({ $natural: 1 })

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.