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

asked Jul 21, 2016 at 16:01
2

1 Answer 1

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}})
mustaccio
28.6k24 gold badges60 silver badges77 bronze badges
answered Aug 23, 2016 at 15:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.