Discussion on several different query methods in MongoDB

Source: Internet
Author: User
Keywords Nbsp; fact name Array can

&http://www.aliyun.com/zixun/aggregation/37954.html ">nbsp;1.find

MongoDB uses find to query. The query returns a subset of the files in the set, with a child collection ranging from 0 documents to the entire collection. The first parameter of find

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

The empty query document {} will match the entire contents of the collection. If you do not specify a query document, the default is {}.

such as: Db.users.find () returns all content in the collection users.

Adding a key-value pair to a query document means adding a query condition. For most types, integers match integers, Boolean types match Boolean types, string matches

String.

2. Specifies the returned key

It is sometimes not necessary to return all the key value pairs in the document. You can specify the key to return by using the second argument of Find or findone. This will save the transmission.

Data volume, but also can save the client decoding the document time and memory consumption.

Db.users.findOne ({"Name": "Refactor"},{"age": 1, "Sex": 1})

Only data returned by the key is _id,age,sex.

The "_id" key is always returned.

You can also use the second argument to remove a key value pair from the query result.

As:

Key name does not appear in returned results

Db.users.findOne ({"Name": "Refactor"},{"name": 0})

Only the data with the key Age,sex is returned. _id "Key is not returned

Db.users.findOne ({"Name": "Refactor"},{"age": 1, "Sex": 1, "_id": 0})

3. Query conditions

"$lt", "$lte", "$gt", "$gte" respectively correspond to <,<=,>,>=

As:

Query Age >=18 <=30

Db.users.find ({"Age": {"$gte": "$lte": 30}})

Add key to document birthday

db.users.update ({"Name": "Refactor"}, {"$set": {"Birthday": New Date ("1989/10/26")}})

Query birthday date is 1990-1-1 ago

Db.users.find ({"Birthday": {"$lt": New Date ("1990/01/01")}})

Use the $ne

Find all documents with name Refactor1 and note that documents that do not have key name are also detected

Db.users.find ({"name": {"$ne": "Refactor1"}})

Using or querying

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

Use the $in

Query for pageviews 10000,20000 data

Db.users.find ({pageviews:{"$in": [10000,20000]}})

"$in" can specify different types of conditions and values, such as a query that will do both if the user's ID number is being migrated to the user name:

Db.users.find ({"user_id": {"$in": [12345, Refactor]}})

This will match user_id 12345 and "refactor" documents.

If the array of "$in" has only one value and the value of the direct match is the same, the effect is the same.

Db.users.find ({"pageviews": {"$in": [10000]}}) Db.users.find ({"pageviews": 10000})

Use $nin to return a document that does not match all of the criteria in the array

If you detect all pageviews 10000,20000 documents, note that the document does not exist key pageviews documents will also be detected

Db.users.find ({"pageviews": {"$nin": [10000,20000]}})

"$in" Enables or queries a single key.

Use the $or

Db.users.find ({"$or": [{"pageviews": {"$in": [10000,20000]}}, {"url": "Http://www.cnblogs.com/refactor"}]})

This will query for documents that pageviews are 10000,20000 or URLs that are http://www.cnblogs.com/refactor.

Note: When using common and queries, try to put the most demanding conditions ahead.

Use the $not

"$not" can be used on any condition.

As:

Db.users.find ({"Id_num": {"mod": [5,1]}})

This will query for a document with a value of 1 after id_num modulo.

Db.users.find ({"Id_num": {"$not": {"mod": [1,5]}})

4. Rules of Conditional sentences

In the query, "$LT" is in the inner document, and in the update "$inc" is the key of the outer document.

A conditional sentence is the key of an inner document, and the modifier is the key to the outer document.

Multiple conditions can be applied to a key, but a key cannot correspond to multiple update modifier.

5. Type-specific queries

Null can match itself and can match "nonexistent"

Documents that can detect that the URL is "http://www.cnblogs.com/refactor" and pageviews null

db.users.find ({"url": "Http://www.cnblogs.com/refactor", "pageviews": null})

can detect pageviews null documents, there is no key pageviews can also be found

Db.users.find ({"pageviews": null})

Can find the URL is "Http://www.cnblogs.com/refactor", pageviews null document, but can not detect the absence of key pageviews documents
Db.users.find ({"url": "Http://www.cnblogs.com/refactor", "pageviews": {"$in": [null], "$exists": True}})

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

If you only want to match a document that has a null key value, check that the value of the key is null, and that the key exists through the $exists condition.

6. Regular expressions

Regular expressions can be flexible and efficient in matching strings.

Find all users with refact or refact names, using regular expressions to perform ignore case matching

Db.users.find ({"Name":/refact/i})

The system can accept regular expression identifiers (i), but not necessarily. Now it matches all the refact in the case.

MongoDB can create an index for a prefix regular expression (such as:/^refactor/) query. So this type of query is very efficient.

Regular expressions can also match themselves

As

Db.users.find ({"Name":/refact/})

You can find documents with name/refact/.

7. Query array

Arrays can be understood in most cases: Each element is the value of the entire key.

Db.users.findOne ({"UserName": "Refactor", "emails": "295240648@qq.com"}) can match to

Use the $all

If you need multiple elements to match an array, use the "$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 a document with "295240648@163.com" and "295240648@126.com" in the mailbox, the order does not matter.

Db.users.find ({"emails": {"$all": ["295240648@163.com", "295240648@126.com"]}})

If you use "$all" only on an array of elements, it is the same as without the "$all", as

Db.users.find ({"emails": {"$all": ["295240648@126.com"]}) Db.users.find ({"Emails": "295240648@126.com"})

The effect is the same.

You can also match arrays exactly

Db.users.find ({"UserName": "Refactor", emails:["295240648@qq.com", "295240648@163.com", "295240648@126.com"]})

To query the element at the specified location of the array, you need to specify the subscript using the Key.index syntax

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

Use the $size

$size can query an array of specified lengths

Query array with an array length of 3

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

The common query is the array length range of queries. $size "cannot be combined with other query clauses (for example," $GT "), but such queries can be

Add a "size" key to the document to implement. This adds the "size" value each time the element is added to the specified array. So it turns out

Update:

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

Become such an update:
Db.users.update ({"$push": {"emails": "295240648@139.com"}, "$inc": {"size": 1}})

So you can query

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

Use the $slice query

The second parameter of find is optional, you can specify which keys to return, and "$slice" returns a child collection of the array

Returns the first two elements of the emails array

Db.users.find ({"UserName": "Refactor"},{"emails": {"$slice": 2}})

Returns the latter two elements of the emails array

Db.users.find ({"UserName": "Refactor"},{"emails": {"$slice":-2}})

Returns the 2nd and 11th elements of the emails array. If the array is not 11, return all elements after 2nd

Db.users.find ({"UserName": "Refactor"},{"emails": {"$slice": [1,10]}})

$slice defaults to return all keys in the document.

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.