0

Does Mongo ensure the order of cursor, while performing $in query?

Say this is my query:

db.collection.find({"_id":{"$in":["a","b","c"]}});

If there are three documents matching this query, how is its order expected to be? Query order? Or inserted order? Or modified order? Or some random order?

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
Sree Karthik S R
  • 335
  • 2
  • 3
  • 10

2 Answers2

1

Actually, without a sort operation attached, they will be returned in natural order.

In general, if you need to have them returned in a specific order, you should state this explicitly:

db.collection.find({"_id":{"$in":["a","b","c"]}}).sort({_id:1});

Which should give you the result set in order a,b,c (assuming that you have a match for all of the queried _ids). And it is even cheap, since it will make use of an index.

Speaking about indexing: If you sort by another field, there should be an index incorporating that field. So if you have a query like

db.collection.find({"_id":{"$in":["a","b","c"]}}).sort({foo:-1});

There should be an index created like

db.collection.createIndex({_id:1,foo:-1})

MongoDB Mantra of the day

Order matters.

In this case, even twice: The sort order and the order of the keys within the index, which needs to reflect the order of the keys in the query.

Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89
0

The order is undefined.

Usually you will get what looks like insertion order, but you can not rely on this. Various events can lead to the order getting mixed up.

When you want your results to be sorted, sort them explicitly. When you .sort({_id:1}), the default index on _id will be used to speed up this sort, so the performance cost will be low.

Philipp
  • 67,764
  • 9
  • 118
  • 153