1

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

1

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}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.