Several different query methods in MongoDB

Source: Internet
Author: User
Tags findone mongodb setup

1. find

MongoDB uses find for query. The query is to return a subset of the documents in a collection. The range of the child set is from 0 documents to the first parameter of the entire set. find.

Determines which documents are to be returned. The form is also a document that describes the details to be queried.

The empty query document {} matches all the content of the set. If no query document is specified, the default value is {}.

For example, db. users. find () returns all content in the Set users.

Adding a key-value pair to the query document means that the query conditions are added. For the vast majority of types, the integer matches the integer, the Boolean matches the Boolean, and the string matches

String.

2. Specify the keys returned

Sometimes you do not need to return all key-value pairs in the document. You can use the second parameter of find or findOne to specify the key to be returned. This can save Transmission

Data size, saving the client time and memory consumption for decoding documents.

 
 
  1. db.users.findOne({"name":"refactor"},{"age":1,"sex":1}) 

Only data with the key _ id, age, and sex is returned.

The "_ id" key is always returned.

You can also use the second parameter to remove a key-value pair in the query results.

For example:

The key name is not displayed in the returned results.

 
 
  1. db.users.findOne({"name":"refactor"},{"name":0}) 

Only the key is age, and the sex data is returned. The "_ id" key is not returned.

 
 
  1. db.users.findOne({"name":"refactor"},{"age":1,"sex":1,"_id":0}) 

3. query Conditions

"$ Lt", "$ lte", "$ gt", "$ gte" correspond to <, <=,>,> =

For example:

Query age> = 18 <= 30

Db. users. find ({"age": {"$ gte": 18, "$ lte": 30 }})

Add the birthday key to the document

 
 
  1. db.users.update( 
  2. {"name":"refactor"}, 
  3. "$set": 
  4. "birthday":new Date("1989/10/26") 

Query the person whose birthday is earlier

 
 
  1. db.users.find({"birthday":{"$lt":new Date("1990/01/01")}}) 

Use "$ ne"

Find all documents with names ranging from refactor1. Note that documents with no key name will also be found.

 
 
  1. db.users.find({"name":{"$ne":"refactor1"}}) 

Use or to query

MongoDB can use "$ in", "$ or"

Use "$ in"

Query the data with pageViews as bytes and 20000

 
 
  1. db.users.find({pageViews:{"$in":[10000,20000]}}) 

"$ In" can specify different types of conditions and values. For example, if you are migrating the user's ID number to a user name, you must make both queries:

 
 
  1. db.users.find({"user_id":{"$in":[12345,"refactor"]}}) 

This will match the document in which user_id is 12345 and "refactor.

If the "$ in" array has only one value and directly matches this value, the effect is the same.

 
 
  1. db.users.find({"pageViews":{"$in":[10000]}}) 
  2. db.users.find({"pageViews":10000}) 

Use "$ nin" to return a document that does not match all the conditions in the array

If you find all documents with pageViews ranging from to, note that the document without the key pageViews will also be found.

 
 
  1. db.users.find({"pageViews":{"$nin":[10000,20000]}}) 

"$ In" can query or for a single key.

Use "$ or"

 
 
  1. db.users.find( 
  2. "$or": 
  3. {"pageViews":{"$in":[10000,20000]}}, 
  4. {"url":"http://www.cnblogs.com/refactor"} 

This will query the document where pageViews are logs, 20000, or url is http://www.cnblogs.com/refactor.

Note: When using a common and query, try to put the most stringent conditions in front.

Use "$ not"

"$ Not" can be used on any condition.

For example:

 
 
  1. db.users.find( 
  2. {"id_num":{"mod":[5,1]}} 

This will query the document whose id_num modulo value is 1.

 
 
  1. db.users.find( 
  2. {"id_num":{"$not":{"mod":[1,5]}}} 

4. Condition sentence rules

In the query, "$ lt" is the internal document. In the update, "$ inc" is the key of the outer document.

The condition is the key of the inner document, and the modifier is the key of the outer document.

Multiple conditions can be applied to one key, but one key cannot correspond to multiple update modifiers.

5. type-specific queries

Null can match itself, and it can match "nonexistent"

It can be found that the url is "http://www.cnblogs.com/refactor", pageViews is null document

 
 
  1. db.users.find({"url":"http://www.cnblogs.com/refactor","pageViews":null}) 

The document with pageViews being null can also be found if the key pageViews does not exist.

 
 
  1. db.users.find({"pageViews":null}) 

Can identify the url is "http://www.cnblogs.com/refactor", pageViews is null document, but cannot find the document without the key pageViews
Db. users. find ({"url": "http://www.cnblogs.com/refactor", "pageViews": {"$ in": [null], "$ exists": true }})

MongoDB does not have the "$ eq" operator, but only one element has the same "$ in" operation effect.

If you only want to match a document whose key value is null, you must check whether the key value is null and determine whether the key exists through the "$ exists" condition.

6. Regular Expression

Regular Expressions can flexibly and effectively match strings.

Search for all users whose names contain refact or Refact and use a regular expression to perform case-insensitive matching.

 
 
  1. db.users.find({"name":/refact/i}) 

The system can accept regular expression Identifiers (I), but not necessarily. Now it matches refact in various case formats.

MongoDB can create indexes for prefix Regular Expressions (for example,/^ refactor/). Therefore, this type of query is very efficient.

Regular Expressions can also match themselves.

For example

 
 
  1. db.users.find({"name":/refact/}) 

You can find the document whose name is/refact.

7. query Arrays

In most cases, the array can be understood as follows: each element is the value of the entire key.

Db. users. findOne ({"userName": "refactor", "emails": "295240648@qq.com"}) can match

Use "$ all"

If you need multiple elements to match the array, you must use "$ all"

Db. users. insert ({"userName": "refactor", emails: ["295240648@qq.com", "295240648@163.com", "295240648@126.com"]})
Db. users. insert ({"userName": "refactor", emails: ["295240648@qq.com", "295240648@126.com", "295240648@111.com"]})
Db. users. insert ({"userName": "refactor", emails: ["295240648@126.com", "295240648@163.com", "295240648@111.com"]})

To find documents in which the mailbox has "295240648@163.com" and "295240648@126.com", the order is irrelevant

 
 
  1. db.users.find( 
  2. "emails": 
  3. "$all": 
  4. "295240648@163.com", 
  5. "295240648@126.com" 

If "$ all" is used only for an array of one element, it is the same as "$ all", for example

 
 
  1. db.users.find({"emails":{"$all":["295240648@126.com"]}}) 
  2. db.users.find({"emails":"295240648@126.com"}) 

The results are the same.

You can also precisely match the array.

 
 
  1. db.users.find({"userName":"refactor",emails:["295240648@qq.com","295240648@163.com","295240648@126.com"]}) 

To query the elements at the specified position of an array, you must use the key. index syntax to specify the subscript.

Db. users. find ({"emails.1": "295240648@163.com "})

Use "$ size"

"$ Size" can be used to query arrays of a specified length

Queries an array with a length of 3.

Db. users. find ({"emails": {"$ size": 3 }})

A common query is an array length range query. "$ size" cannot be combined with other query clauses (for example, "$ gt ").

Add a "size" key in this document to add the "size" value to the specified array.

Update:

Db. users. update ({"$ push": {"emails": "295240648@139.com "}})

The update is as follows:
Db. users. update ({"$ push": {"emails": "295240648@139.com"}, "$ inc": {"size": 1 }})

In this way, you can query

Db. users. find ({"size": {"$ gt": 3 }})

Use "$ slice" to query

The second parameter of find is optional. You can specify the keys that are returned. "$ slice" returns a subset of the array.

Returns the first two elements of the emails array.

 
 
  1. db.users.find({"userName":"refactor"},{"emails":{"$slice":2}}) 

Returns the last two elements of the emails array.

 
 
  1. db.users.find({"userName":"refactor"},{"emails":{"$slice":-2}}) 

Returns the 2nd and 11th elements of the emails array. If there are less than 11 elements in the array, all elements following the 2nd elements are returned.

 
 
  1. db.users.find({"userName":"refactor"},{"emails":{"$slice":[1,10]}}) 

"$ Slice" returns all keys in the document by default.

Edit recommendations]

  1. MongoDB 2.0 official version released
  2. View the Compact Command one by one in the new functions of MongoDB 2.0
  3. Comprehensive Evaluation of mainstream NoSQL databases-MongoDB
  4. How to use MySQL to learn MongoDB
  5. MongoDB setup and simple operations in Windows

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.