Are Fields in MongoDB documents sorted in order?
In this article, we will briefly discuss the sequence of fields in Mongodb. The document in Mongodb is a Json string consisting of Key: Value pairs. It is reasonable to say that the order of fields should not affect the query operation.
Let's simply make an experiment and insert a record into the set:
Db. testcollection. insert ({"apple": 2, "banana": 3 });
At this time, we use the following two methods to query the same:
Method 1:
Db. testcollection. find ({"apple": 2, "banana": 3 })
Method 2:
Db. testcollection. find ({"banana": 3, "apple": 2 })
You can query the results in either of the above two methods, both of which are the same record. Is there any difference in the field order? Don't worry. Let's look at another example.
For example, we inserted the following record in the collection:
Db. testcollection. insert ({"type": "fruit", "detail": {"apple": 2, "banana": 3 }});
In this case, we use the following two methods for query:
Method 1:
Db. testcollection. find ({"detail": {"apple": 2, "banana": 3 }})
Method 2:
Db. testcollection. find ({"detail": {"banana": 3, "apple": 2 }})
The results of the two query methods are different. The first method queries the results, but the second method does not. From this example, we can tell you that when we query a collection with nested documents, we should pay a little attention to it. Otherwise, the above situation may occur.
How can we avoid different query results due to the writing order above? There is a way, that is, do not use a json string for query. In such a set with nested documents, you can use the dot symbol for operations, we use the following two methods for query.
Method 1:
Db. testcollection. find ({"detail. apple": 2, "detail. banana": 3 })
Method 2:
Db. testcollection. find ({"detail. banana": 3, "detail. apple": 2 })
The results show that the results of these two queries are the same. It can be seen that for simple queries or queries with nested documents, it is not suitable to use Json string writing format for Field Values in query strings, but to use point numbers for nested reference queries, this prevents query errors caused by different field order in the document and the field order in the document.
For more MongoDB tutorials, see the following:
CentOS compilation and installation of php extensions for MongoDB and mongoDB
CentOS 6 install MongoDB and server configuration using yum
Install MongoDB2.4.3 in Ubuntu 13.04
MongoDB beginners must read (both concepts and practices)
MongoDB Installation Guide for Ubunu 14.04
MongoDB authoritative Guide (The Definitive Guide) in English [PDF]
Nagios monitoring MongoDB sharded cluster service practice
Build MongoDB Service Based on CentOS 6.5 Operating System
MongoDB details: click here
MongoDB: click here
This article permanently updates the link address: