MongoDB duplicate “_id ” for an array “_id”

mongodbmongodb-3.0

Consider db "test" in my standalone mongodb instance.
I created a collection called testCol and inserted a document with the following syntax :

db.testCol.insert({_id:{"age":22,"empId":1},"DOJ":"22JUL"})

which results in :

WriteResult({ "nInserted" : 1 })

and upon quering

db.testCol.find()

I get

{ "_id" : { "age" : 22, "empId" : 1 }, "DOJ" : "22JUL" }

However upon inserting another document with the same _id with different positioning of the array elements with syntax :

db.testCol.insert({_id:{"empId":1,"age":22},"DOJ":"22JUL"})

which results in :

WriteResult({ "nInserted" : 1 })

and upon quering the collection using

db.testCol.find()

I get

{ "_id" : { "age" : 22, "empId" : 1 }, "DOJ" : "22JUL" }
{ "_id" : { "empId" : 1, "age" : 22 }, "DOJ" : "22JUL" }

Is this a bug because to query the document with the unique _id using the syntax :

db.testCol.find({"_id.age":22,"_id.empId":1})

will return

{ "_id" : { "age" : 22, "empId" : 1 }, "DOJ" : "22JUL" }
{ "_id" : { "empId" : 1, "age" : 22 }, "DOJ" : "22JUL" }

Why is this happening ? If mongodb follows a specific _id structure then shouldn't it return only 1 document from the final find command and if mongodb doesn't follow a specific structure then how does it let me insert multiple documents

Best Answer

I realised order matters to MongoDB when using an object as the value for a unique field such as the _id field.

Not sure if it can be termed a bug.

That said, with reference to your query:

db.testCol.find({"_id.age":22,"_id.empId":1})

what you are actually doing is querying based on individual components of the _id field and not the _id field as a whole.

You will be better served if your query targets the _id as a whole. This query should achieve what you intended.

db.testCol.find({"_id": {"age" : 22, "empId" : 1}})