Julien L
Julien L

Reputation: 53

WiredTiger MongoDB engine ordering : Is" natural order" equivalent to "ordered" with WiredTiger engine in mongodb?

Here is the concrete reason for this question :

db.collection.findOne() function is documented as :

"If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk".

According to http://docs.mongodb.org/manual/reference/method/cursor.sort/#mmapv1 this notion of natural order seems to fit only to MMAPv1 and not to apply to wiredTiger.

Then, I would like to know if using db.collection.findOne() with wiredTiger will always return the first indexed document (the one with the lowest _id index) that matches the search criteria.

-> Then findOne() would be equivalent to "findFirst() according to _id" , and ordering will be guaranted : Is that correct ?

Thanks,

Julien

Upvotes: 3

Views: 498

Answers (2)

wdberkeley
wdberkeley

Reputation: 11671

Instead of worrying about exactly what defines natural order, I would instead think of it as "whatever the database wants to do at that instant". You should never depend on natural order, since you have pretty much no guarantees about how it's going to return documents, especially if you are comparing storage engines. It's not an order based on insertion time, though it could be; it's not an order based on location on disk, though it could be; and it's not an order based on _id, though it could be. It just returns documents however the implementers decide is best or easiest based on there being no specific order requested, hence why it is called "natural". Since it's an implementation detail, it could change at any point.

I would like to know if using db.collection.findOne() with wiredTiger will always return the first indexed document (the one with the lowest _id index) that matches the search criteria

No. If you want the smallest _id, explicitly order on ascending _id and take the first result. You always have the _id index for this.

Upvotes: 2

marijnz0r
marijnz0r

Reputation: 934

Natural means in order of inserting, NOT by order of id. The doc doesn't say it's not working for WiredTiger, so I assume it works for this storage engine as well:

Use the $natural operator to use natural order for the results of a sort operation. Natural order refers to the logical ordering of documents internally within the database.

Upvotes: -1

Related Questions