Thursday, June 30, 2016

Different Key orders make the document different in MongoDB?

[mongod@localhost ~]$ mongo test
MongoDB shell version: 3.2.6
connecting to: test

> db.mycol.drop()
False


> db.mycol.insert({'_id':1,x:1,y:2,z:3})
WriteResult({ "nInserted" : 1 })
> db.mycol.insert({'_id':3,y:2,z:3,x:1})
WriteResult({ "nInserted" : 1 })


> db.mycol.find().pretty()
{ "_id" : 1, "x" : 1, "y" : 2, "z" : 3 }
{ "_id" : 3, "y" : 2, "z" : 3, "x" : 1 }


> db.mycol.createIndex({x:1,y:1,z:1},{unique:true})
{
        "ok" : 0,
        "errmsg" : "E11000 duplicate key error collection: test.mycol index: x_1_y_1_z_1 dup key: { : 1.0, : 2.0, : 3.0 }",
        "code" : 11000
}

> db.mycol.find({x:1,y:2,z:3})
{ "_id" : 1, "x" : 1, "y" : 2, "z" : 3 }
{ "_id" : 3, "y" : 2, "z" : 3, "x" : 1 }

> db.mycol.find({x:1,y:2,z:3},{x:1,y:1,z:1})
{ "_id" : 1, "x" : 1, "y" : 2, "z" : 3 }
{ "_id" : 3, "y" : 2, "z" : 3, "x" : 1 }


// some proper formatting by re-arranging the column/key names
> db.mycol.aggregate([{$match:{x:1,y:2,z:3}},{$project:{xx:"$x",yy:"$y",zz:"$z"}},{$project:{x:"$xx",y:"$yy",z:"$zz"}}])
{ "_id" : 1, "x" : 1, "y" : 2, "z" : 3 }
{ "_id" : 3, "x" : 1, "y" : 2, "z" : 3 }