Reputation: 811
Query result doesn't maintain the order as per the insertion order if it contains individual indexes. If the mongo Query contain composite indexes, will the result data order is maintained as per the insertion order?
Upvotes: 0
Views: 238
Reputation: 12240
If you need to preserve insertion order in a collection you need to use capped collections. For capped collections MongoDB automatically preserves the insertion order.
From the capped collection docs:
Capped collections guarantee preservation of the insertion order. As a result, queries do not need an index to return documents in insertion order. Without this indexing overhead, they can support higher insertion throughput.
Capped collections guarantee that insertion order is identical to the order on disk (natural order) and do so by prohibiting updates that increase document size. Capped collections only allow updates that fit the original document size, which ensures a document does not change its location on disk.
Capped collections automatically remove the oldest documents in the collection without requiring scripts or explicit remove operations.
But capped collections have some major drawbacks:
Upvotes: 1
Reputation: 43884
It doesn't matter if you have a unique index or not, MongoDB WILL NOT return in insertion order unless you sort with an index which is representative of insertion order (a unique index actually isn't, it is a special type of index).
Instead it will return in natural order (not actually $natural
since that is a type of disk order).
This natural order is in fact the order specified by the internal linked lists as I actually explained here: Mongo 2.6 indexing - query result order and as @kwolfe explained how to actually get sorted results.
Upvotes: 3
Reputation: 151072
The index chosen will depend on the fields used in your query and the order of results will be reflected by the index ordering.
So with data like this:
{ "a": 5, "b:" 2 }
{ "a": 5, "b": 1 }
{ "a": 1, "b": 7 }
And a compound index:
db.collection.ensureIndex({ "a": 1, "b": 1 })
A query that can use this index will order the fields by the index in the result:
{ "a": 1, "b": 7 }
{ "a": 5, "b": 1 }
{ "a": 5, "b:" 2 }
If you want to keep the insertion order then you can use the $natural
modifier in the .sort()
:
db.collection.find({ a: { "$gte": 1 } }).sort({ "$natural": 1 })
To order by how the documents are found on disk. Or you can simply just specify the _id
as the "sort"
db.collection.find({ a: { "$gte": 1 } }).sort({ "_id": 1 })
This will force the order of the results to maintain their insertion order by the _id
key and it's increasing value. Requiring of course that that is true, which it should be if you are using the default ObjectId
implementation.
Upvotes: 1