Get the App
SLTechnology News&Howtos  ›  Database  › 

[MongoDB Learning Notes 23] indexed objects and arrays of MongoDB

Shulou Source: shulou.com Published: 2022-06-01 16:15:15 09月15日 Update

MongoDB allows you to go deep inside the document, indexing nested fields and arrays; nested objects and array fields can be used with top-level fields in a composite index, and in most cases behave in the same way as "normal" index fields.

I. indexing nested documents

For example, the documents in the collection are in the following format

> db.post.findOne ({"username": "sid") {"_ id": ObjectId ("54aff7f43bd1048e7b585e39"), "username": "sid", "loc": {"ip": "1.2.3.4", "city": "springfield", "state": "ny"}} >

You need to build an index on the city of "loc" to speed up the query for this loc.city field:

> db.post.ensureIndex ({"loc.city": 1}) {"createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1} >

Indexes of any depth can be built in this way, for example, indexes can be built on X.Y.Z.A.B.C.

However, an index built on a subdocument "loc" is different from an index built on a field "loc.city" in a subdocument:

(1) the index established on the whole subdocument will only improve the query speed of the whole subdocument; that is to say, the subdocument index will work only if the query (including the order of fields) perfectly matches the subdocument.

(2) Index loc.city works only when querying the loc.city field, while index loc.city does not work in other cases.

2. Indexes on arrays

(1) it can be seen that the cost of establishing an index on an array field is relatively high, because each deletion and update will refresh each index, which consumes too much server resources.

(2) you can do a specific individual index on an element in the array field to reduce the number of indexes; for example, index on votes in the ninth element in the array field comments:

> db.post.ensureIndex ({"comment.10.votes": 1})

Similarly, the above index will play the role of an index only if it exactly matches the comment.10.votes query.

3. Multi-key index

If you create an index on an array field, the index is called a multikey.

In the multi-key index reference explain function, you can see that the value of the "isMultikey" field is true, and the multi-key index is slower than the non-multi-key index.

Tags: Index field document array query function only size element situation speed object different precise consistent that is cost function and number Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Xiaomi Shulou Tech Info macOS