Skip to content

Instantly share code, notes, and snippets.

@cezarsa
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cezarsa/0c1106ee32ee7b12914c to your computer and use it in GitHub Desktop.
Save cezarsa/0c1106ee32ee7b12914c to your computer and use it in GitHub Desktop.

After creating an index in a capped collection, sorting it in reverse natural order doesn't work anymore.

$ mongod --version
db version v2.6.1
2014-06-05T13:45:27.884+0000 git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e8

This works fine and as expected:

> db.createCollection("mycoll", {capped: true, size: 100000, max: 1000})
{ "ok" : 1 }

> for(var i = 0; i < 100; ++i) { db.mycoll.insert({x: i}); }
WriteResult({ "nInserted" : 1 })

> db.mycoll.find({x:{$gt:95}}).sort({$natural: 1})
{ "_id" : ObjectId("5390738c8f5c62869f0775ad"), "x" : 96 }
{ "_id" : ObjectId("5390738c8f5c62869f0775ae"), "x" : 97 }
{ "_id" : ObjectId("5390738c8f5c62869f0775af"), "x" : 98 }
{ "_id" : ObjectId("5390738c8f5c62869f0775b0"), "x" : 99 }

> db.mycoll.find({x:{$gt:95}}).sort({$natural: -1})
{ "_id" : ObjectId("5390738c8f5c62869f0775b0"), "x" : 99 }
{ "_id" : ObjectId("5390738c8f5c62869f0775af"), "x" : 98 }
{ "_id" : ObjectId("5390738c8f5c62869f0775ae"), "x" : 97 }
{ "_id" : ObjectId("5390738c8f5c62869f0775ad"), "x" : 96 }
>

So far so good, now let's create an index:

> db.mycoll.ensureIndex({x: 1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

> db.mycoll.find({x:{$gt:95}}).sort({$natural: 1})
{ "_id" : ObjectId("5390738c8f5c62869f0775ad"), "x" : 96 }
{ "_id" : ObjectId("5390738c8f5c62869f0775ae"), "x" : 97 }
{ "_id" : ObjectId("5390738c8f5c62869f0775af"), "x" : 98 }
{ "_id" : ObjectId("5390738c8f5c62869f0775b0"), "x" : 99 }

> db.mycoll.find({x:{$gt:95}}).sort({$natural: -1})
{ "_id" : ObjectId("5390738c8f5c62869f0775ad"), "x" : 96 }
{ "_id" : ObjectId("5390738c8f5c62869f0775ae"), "x" : 97 }
{ "_id" : ObjectId("5390738c8f5c62869f0775af"), "x" : 98 }
{ "_id" : ObjectId("5390738c8f5c62869f0775b0"), "x" : 99 }
>

The second query in reversed natural order doesn't work anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment