Article 2: Advanced MongoDB Query

Source: Internet
Author: User
Tags mongodb query

This section describes how to perform advanced queries on MongoDB in the console, including the tutorial content, hands-on experience with me labs, and understanding these rules. For other languages (Java, ruby, Python, etc.) is of great help in implementing queries, because the basics are the same, but the interfaces implemented in different languages are slightly different.

I would like to remind you that more hands-on experiments are the best practice.

<,>, >=, <=

There is no need to explain the four, the most common and simplest.

DB. collection. Find ({"field": {$ GT: Value}) // greater than: field> Value

DB. collection. Find ({"field": {$ LT: Value}) // less than: Field <Value

DB. collection. Find ({"field": {$ GTE: Value}) // greater than or equal to: field> = Value

DB. collection. Find ({"field": {$ LTE: Value}) // less than or equal to: Field <= Value

If you want to meet multiple conditions at the same time, remember to use the following:

DB. collection. Find ({"field": {$ GT: value1, $ LT: value2}) // value1 <field <Value

$ Ne is not equal

DB. Things. Find ({x :{$ ne: 3 }})

The condition is equivalent to x <> 3, that is, X is not equal to 3.

$ Mod modulo operation

DB. Things. Find ({A: {$ mod: [10, 1]})

The condition is equivalent to a % 10 = 1, that is, dividing a by 10 remainder to 1.

$ Nin does not belong

DB. Things. Find ({J: {$ Nin: [2, 4, 6]})

The condition is equivalent to J not equal to any of [2, 4, 6.

$ In belongs

DB. Things. Find ({J: {$ in: [2, 4, 6]})

The condition is equivalent to any of [2, 4, 6.

$ All belongs

DB. Things. Find ({A :{$ All: [2, 3] }})

Similar to $ in, but all values that must be [] exist.

$ Size quantity, size

DB. Things. Find ({A: {$ size: 1 }})

The number of conditions equivalent to the value of A is 1 (A must be an array, and a value cannot be regarded as an array with the number of 1 ).

$ Exists field exists

DB. Things. Find ({A :{$ exists: true }})

DB. Things. Find ({A :{$ exists: false }})

True: return data with field A. False: return data with no degree.

$ Type field type

DB. Things. Find ({A: {$ type: 2 }})

If the condition is that the type is correct, data is returned.

The parameter type is as follows:

Type name type number double 1 string 2 object 3 Array 4 binary data 5 Object ID 7 Boolean 8 date 9 null 10 regular expression 11 JavaScript code 13 symbol 14 JavaScript code with scope 15 32-bit integer 16 timestamp 17 64-bit integer 18 min key 255 max key 127

Regular Expressions Regular Expression

DB. Customers. Find ({Name:/acme. * Corp/I })

Similar to the like method in SQL.

Row start/^ row end $/

Pay special attention to the following points:

While/^ A/,/^. /, And/^. $/are equivalent and will all use an index in the same way, the later two require scanning the whole string so they will be slower. the first format can stop scanning after the prefix is matched.

It means that when you query a string starting with a, there are three forms:/^ A/,/^ A./, And/^ A. $ /. The following two forms scan the entire string and the query speed slows down. The first form will stop scanning for subsequent characters after a matching start is found.

Pay special attention to this.

Several additional parameters:

I means case-insensitive. (This is very important and often used)

M indicates that multiple rows are supported. (But I have not tried it)

X indicates the extension. (And never used)

$ Or (Note: MongoDB 1.5.3 and later versions are available)

DB. Foo. Find ({$ or: [{A: 1}, {B: 2}]})

Data that meets the condition A = 1 or B = 2 will be queried.

Query with other fields:

DB. Foo. Find ({name: "Bob", $ or: [{A: 1 },{ B: 2}]})

The data that meets either of the other two conditions is equal to Bob.

Value in an array

For example, the database contains such data:

{"_ Id": objectid ("4c503405645fa23b31e000031"), "Colors": ["red", "black"]}

Query

DB. Things. Find ({colors: "red "});

You can find the data above.

$ Elemmatch

T. Find ({x :{$ elemmatch: {A: 1, B :{$ GT: 1 }}}})

Result:

{"_ Id": objectid ("4b5783300334000000000aa9 "),

"X": [{"A": 1, "B": 3}, 7, {"B": 99 },{ "A": 11}]

}

X one of the elements can be retrieved if they meet the search criteria. (But who uses a structure like X to save data ?)

Value in an embedded object

For example, the database contains such data:

{"_ Id": objectid ("4c503773645fa23b31e000032"), "author": {"name": "Dan Brown", "Age": 38}, "book ": "The Lost Symbol "}

Query:

DB. postings. Find ({"author. Name": "Dan Brown "});

You can find the data above.

To query the attributes of an embedded object, add "". The field is "author. Name" instead of "author. Name.

$ Not

DB. Customers. Find ({Name: {$ not:/acme. * Corp/I }});

This is an operator used in combination with other query conditions and is not used independently.

As long as you understand the previous query operation, but add $ not, the result is the opposite result set without $ not.

Sort () sorting

This is very practical. That is, orderby in SQL.

DB. mycollection. Find (). Sort ({ts:-1 })

You can also sort multiple fields.

DB. mycollection. Find (). Sort ({ts:-1, DS: 1 })

1 indicates ascending, and-1 indicates descending.

In my experiments, numbers smaller than 0 are in descending order, and numbers greater than 0 (including 0) are in ascending order.

Limit () SKIP ()

These two me will be a good helper for you to implement database paging.

Limit () controls the number of returned results. If the parameter is 0, it is treated as no constraint and limit () does not work.

Skip () controls the number of skipped results returned. If the parameter is 0, it is treated as no constraint. Skip () does not work, or 0 is skipped.

For example:

DB. Test. Find (). Skip (5). Limit (5)

The result is 6th to 10th data records.

Snapshot () (no attempt)

Count ()

Number of returned result sets.

DB. Test. Count ()

When you add the SKIP () and limit () operations, you need a parameter of true to obtain the actual number of returned results. Otherwise, the total number of results that meet the query conditions is returned.

Example:

> DB. Test. Find (). Skip (5). Limit (5). Count ()

9

> DB. Test. Find (). Skip (5). Limit (5). Count (true)

4

Translated from http://www.mongodb.org/display/docs/advanced?queries=content.

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.