Indexing on an object value field

Hello @Sachin_Kumar_Verma,

I think the index will work perfectly, but the query will not, you have to understand the below things if you don’t know,
Consider you have documents in the collection:

[{ 
  "_id": "1",
  "status": { "id": 1, "name": "Draft" } 
},
{ 
  "_id": "2",
  "status": { "name": "Draft", "id": 1 } 
}]

Your query is:

find({ "status": { "id": 1, "name": "Draft" } })

You will get a single document, as you can see the below result:

[{ 
  "_id": "1",
  "status": { "id": 1, "name": "Draft" } 
}]

Why? Because the order of status’s value property is not equal to the original document in the collection,

{ "id": 1, "name": "Draft" }  not equal to { "name": "Draft", "id": 1 }

So you have to make sure that your insert query should always store the status’s value object in the same order.

MongoDB compares objects as values, so it is not like JS!


Out of the question:
I would suggest you experiment with these things using the MongoDB Compass, It’s easy and quick to connect your cluster, insert documents, execute queries (find, aggregate), create indexes, explain query by explain command to check does your query used index or not.

5 Likes