MongoDB Advanced Query and Index

Source: Internet
Author: User
Tags mongodb query

Organize from

Https://www.shiyanlou.com/courses/running/78

Overwrite index query

All query fields are part of the index, and all query return fields are in the same index.

Because the index exists in RAM, getting data from the index is faster than scanning the surface document

Example: Create the following Users collection (create the collection using the method you learned earlier):

{   "contact": "987654321",   "dob": "01-01-1991",   "gender": "M", "name": "Tom Benzamin", "user_name": "tombenzamin"}

Create a federated index in user

db.users.ensureIndex({gender:1,user_name:1})

The index overwrites the following query:

db.users.find({gender:"M"},{user_name:1,_id:0})

For the above query, MongoDB does not look in the database file, but extracts the data from the index. Because the _id field is not included in the index, _ID is returned by default in the query and can be excluded from the query results. And will db.users.find({gender:"M"},{user_name:1}) not be overwritten by the index

Advanced Index

Create the following users collection (create the collection using the method you learned earlier):

{   "address": {      "city": "chengdu", "province": "sichuan", "pincode": "123" }, "tags": [ "music", "cricket", "blogs" ], "name": "clound"}

An indexed array field that creates an index in an array that needs to be indexed in turn for each field in the set. So when we create an index for an array of tags, we establish separate indexes for music, cricket, blogs three values. Example:

> db.users.ensureIndex({"tags":1})

After the index is created, we can retrieve the tags field of the collection in this way:

db.users.find({tags:"cricket"})

To verify that we used the index, you can use the explain command:

db.users.find({tags:"cricket"}).explain()

"Cursor": "Btreecursor tags_1" appears in the result of the above command execution, indicating that the index has been used.

Indexed sub-document fields

Suppose we need to retrieve the document through the city, state, pincode fields, because these fields are the fields of the subdocument, we need to index the subdocuments. Example: Create an index for the three fields of a subdocument, with the following command:

> db.users.ensureIndex({"address.city":1,"address.province":1,"address.pincode":1})

Once the index is created, we can use the fields of the subdocument to retrieve the data:

> db.users.find({"address.city":"chengdu"})

Remember that the query expression must follow the order of the specified index. So the index created above will support the following query:

> db.users.find({"address.city":"chengdu","address.province":"sichuan"})

The following queries are also supported:

> db.users.find({"address.city":"chengdu","address.province":"sichuan","address.pincode":"123"})
Iv. Atomic operation

The so-called atomic operation is either a successful execution or a failure to perform a successful completion of a given task and perform a failed restore before the execution of the state. Common Atomic operation commands:

$set

Used to specify a key and update the key value if the key does not exist and is created.

{ $set : { field : value } }
$unset

Used to delete a key.

{ $unset : { field : 1} }
$inc

$inc can increase or decrease the number of keys in a document that are numeric (only for numbers that meet the requirements).

{ $inc : { field : value } }
$push

Append value To field, field must be array type, if field does not exist, a new array type will be added.

{ $push : { field : value } }
$pushAll

With $push, it is possible to append multiple values to an array field at a time.

{ $pushAll : { field : value_array } }
$pull

Deletes an equal value from the array field.

{ $pull : { field : _value } }
$addToSet

Adds a value to the array, and only if the value is not inside the array.

$pop

Delete the first or last element of an array

{ $pop : { field : 1 } }
$rename

Modify field names

{ $rename : { old_field_name : new_field_name } }
$bit

Bit operation, integer type

{$bit : { field : {and : 5}}}
V. Query analysis Explain ()

Explain operations provide query information, use indexes and query statistics, and so on. Facilitates our optimization of the index. Next we create indexes for gender and user_name in the Users collection:

db.users.ensureIndex({gender:1,user_name:1})> db.users.find({gender:"M"},{user_name:1,_id:0}).explain()

The fields in the results are explained:

    • IndexOnly: True to indicate that we used the index;
    • Cursor: Because this query uses an index, the index in MongoDB is stored in the B-tree structure, so this is also a cursor of type btreecursor. If the index is not used, the cursor type is basiccursor. This key will also give you the name of the index you are using, you can see the System.indexes collection under the current database (automatically created by the system) to get the detailed information of the index;
    • N: The number of documents returned by the current query;
    • Nscanned/nscannedobjects: Indicates how many documents in the collection are currently scanned by this query, and our goal is to get this number and return document as close as possible;
    • Millis: The time required for the current query, the number of milliseconds;
    • Indexbounds: The index used by the current query.
Hint ()

Although the MongoDB query optimizer generally works well, you can also use hints to force MongoDB to use a specified index. This approach improves performance in some situations. Example: Specify to query using the Gender and User_name index fields:

db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})

You can use the explain () function to parse the above query:

db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()

MongoDB Advanced Query and Index

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.