Brief introduction to MongoDB conditional query instances

Source: Internet
Author: User
Tags mongodb


For example, you can query users whose age is greater than or equal to 20 and whose age is less than 30.

Example

The code is as follows: Copy code
Db. user. find ({"age": {"$ gte": 20, "$ lt": 30 }})

Or query. To query multiple values of a key, for example, if the age is, you can use the $ in operator:

The code is as follows: Copy code

Db. user. find ({"age": {"$ in": [18, 20]});

If $ nin is used above, it means that age is not equal to 18 or 20.
To match multiple keys, you need the $ or operator, for example, query age = 18 or sex = female.

The code is as follows: Copy code

Db. user. find ({"$ or": [{"age": 18 },{ "sex": "female"}]});

$ Mode is a special operator. For example, to retrieve all users with snakes, the 2013 operator means age % 12 = 0.

The code is as follows: Copy code

Db. user. find ({"age": {"$ mod": [12, 0]})

The $ not operator can be used on any condition, for example, to identify non-snake users:

The code is as follows: Copy code

Db. user. find ({"age": {"$ not": {"$ mod": [12, 0]})

In addition, find also supports regular expressions:

The code is as follows: Copy code

Db. user. find ({"name ":/. * j. */I}) db. user. find ({"name ":/. * j. */I })

The above rule matches records with j in all user names. Note that regular expressions do not need to be enclosed by double quotation marks.

You can use the $ elemMatch operator to query the attributes of a document. For example, if the post set comment title is title1 and the content is content1 comment

The code is as follows: Copy code
Db. post. find ({"comments": {"$ elemMatch": {"title": "comment1", "content": "content1 "}}});

Comments is an array document.

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.