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
-
Do I need to enable a specific configuration property; I'm using mongo 3.2.1 with the default configuration propertiesMuzammil H. Momin– Muzammil H. Momin2016年07月21日 16:03:05 +00:00Commented Jul 21, 2016 at 16:03
-
Very good question. The JSON docs say that an object is an unordered set of name/value pairs, and it is generally accepted that the order of fields in a json object is not significant. And MongoDB say that a document's _id must be unique. So yes I think it's a bug, MongoDB is failing on its uniqueness check.Vince Bowdren– Vince Bowdren2016年08月18日 16:11:30 +00:00Commented Aug 18, 2016 at 16:11
1 Answer 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}})