0

I have a collection and I do this query :

db.getCollection("test").find(
{"$or":[{_id:NumberLong("1234")},
        {_id:NumberLong("1230")},
        {_id:NumberLong("1237")},
        {_id:NumberLong("1236")}}
)

In with order will be the returned documents ? I need this exact order (with is the order of the $or statement) :

1234
1230
1237
1236

normally it's the order I see when I do the previous query, but today I saw one query that return me a different order (and this just one time, because after i restarted the server the order was good again). So what to do to have exactly the exact order I need ?

zeus
  • 12,173
  • 9
  • 63
  • 184
  • 1
    It's not guaranteed unless you're explicit about it; it'll be whatever order they were found in unless told otherwise. You can read about ordering options in the docs for your library. – jonrsharpe Jul 20 '18 at 21:49

1 Answers1

1

You have to use $sort to make sure that results are returned in the order you want. Since there's no natural candidate for "sort" field in your model you can use $addFields and add temporary field just for $sort purpose. It can be evaluated using $indexOfArray operator. You can use that field for filtering purpose as well ($indexOfArray returns -1 if there's no match

db.test.aggregate([
    {
        $addFields: {
            order: { $indexOfArray: [ [NumberLong("1234"), NumberLong("1230"), NumberLong("1237"), NumberLong("1236") ], "$_id" ] }
        }
    },
    {
        $match: { order: { $ne: -1 } }
    },
    {
        $sort: { order:1 }
    },
    {
        $project: { order: 0 }
    }
])
mickl
  • 48,568
  • 9
  • 60
  • 89