ltfishie
ltfishie

Reputation: 2987

How can I specify the natural ordering in MongoDB?

Is there a way to specify the natural ordering of data in mongodb, similar to how a primary index would order data in a RDBMS table?

My use case is that all my queries return data sorted by a date field, say birthday. According to MongoDB: Sorting and Natural Order, the natural order for a standard (non-capped) collection is roughly the insertion order, but not guaranteed. This would imply sorting is needed after the data is retrieved.

Upvotes: 1

Views: 3428

Answers (4)

Stennie
Stennie

Reputation: 65313

I believe what you are referring to is a clustered index, not a primary index.

MongoDB 2.0 does not have a clustered index feature, so a regular index on date would be your most efficient option to retrieve.

It's probably premature optimization to think about the physical order on disk with MongoDB. MongoDB uses memory-mapped files, so depending on your working set + queries + RAM you may not need to load data from disk as often as expected.

Upvotes: 1

Aafreen Sheikh
Aafreen Sheikh

Reputation: 5064

I guess it would be difficult to achieve what you want without the help of indexes. To support sharding, the _id field in MongoDB takes values based on the timestamp at the moment the document is created. As a consequence, you can't have them monotonically increasing unlike the identity column in RDBMS table..I think you must create an index on Birthdate column if all your queries return documents sorted in the order of Birthdate. Once the index is created, the queries become efficient enough..
Refer this:
MongoDB capped collection and monotically increasing index

Upvotes: 0

Jason McCay
Jason McCay

Reputation: 3345

Also, I would add that you should look into using the built-in timestamps in the document IDs instead of relying on a separate date field, as it allows you to store less data and removes an index.

Jason MongoHQ

Upvotes: 0

Ben
Ben

Reputation: 9895

If you are looking for something to act like the primary index in a RDBMS then sort by _id. It will be roughly insert order since the _id is prefixed with timestamp. If you try to use $natural order it will cause it to miss indexes.

Upvotes: 1

Related Questions