0

This is my query,

db.getCollection("docs").aggregate(
[
    {$match: {
        userId: ObjectId('55d833edd29d5903005'),
    }},
    {
        $project: { 
            fieldOne: 1,
        },
    },
    {$group: {_id: null, uniqueValues: {$addToSet: "$fieldOne"}}},
    {$sort: {"uniqueValues.fieldOne": -1}},
]
)

The above query display results in random order without my $sort condition. I also used with exec() callback still the same

{$sort: {"uniqueValues.fieldOne": -1}} and {$sort: {"fieldOne": -1}} both doesn't show correct result.. Any idea?

UPDATE 1: Output, each time when I run the order changes

{ 
    "_id" : null, 
    "uniqueValues" : [
        "5674-1", 
        "5621-1", 
        "5445-3", 
        "5572-1", 
        "5490-1", 
        "5537-1",
    ]
}
Prabhakaran
  • 3,900
  • 15
  • 46
  • 113
  • Can you please add some sample data in the question present in the document ? – stud3nt Dec 02 '19 at 10:13
  • @stud3nt added please check – Prabhakaran Dec 02 '19 at 10:21
  • Possible duplicate - https://stackoverflow.com/questions/13449874/how-to-sort-array-inside-collection-record-in-mongodb – stud3nt Dec 02 '19 at 10:24
  • @stud3nt might be but still stuck combining with ``group`` – Prabhakaran Dec 02 '19 at 10:35
  • @overflow : You no longer have `fieldOne` in your document, So `{"uniqueValues.fieldOne": -1}` won't work !! Also you finally have a single document with an array `uniqueValues`, then here what you would like to make an order of ? Is that the values in array ? then `$sort` won't work here, if that's the case you need to move your `$sort` stage up above, Please provide sample docs someone can provide a query if needed.. – whoami - fakeFaceTrueSoul Dec 02 '19 at 17:25

0 Answers0