Advanced query of MongoDB step one

Source: Internet
Author: User

In the previous article we talked about MongoDB's CRUD basic operations http://blog.csdn.net/stronglyh/article/details/46812579

In this case, let's talk about the advanced--------------of MongoDB.

A: Various inquiries

1: Conditional operator

<, <=, >= This operator does not have to explain more, the most commonly used is the 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 equals: field <= value
You can do this if you want to satisfy multiple conditions at the same time

Db.collection.find ({"field": {$gt: value1, $lt: value2}}); value1 < Field < value2

For practice, let's insert a few data.

Db.users.insert ([{name: "Tom", Age:20,sex: "M"},{name: "Lily", Age:40,sex: "F"},{name: "Suby", age:18}]);


2: $all Match all

This operator is similar to the SQL syntax in, but the difference is that in only one value within () is satisfied, and the $all must satisfy all values within [], for example:

Db.users.find ({age: {$all: [6, 8]}});

Can query {name: ' David ', age:26, Age: [6, 8, 9]}

But the query does not show {name: ' David ', age:26, Age: [6, 7, 9]}


3: $exists Determine if a field exists

Querying for data that has field age

> Db.c1.find ({age:{$exists: true});
{"_id": ObjectId ("4fb4a773afa87dc1bed9432d"), "age": +, "Length": 30}


4:null Value Processing

The handling of Null values is slightly odd, depending on the sample data below:

> Db.c2.find ()
{"_id": ObjectId ("4fc34bb81d8a39f01cc17ef4"), "name": "Lily", "Age": null}
{"_id": ObjectId ("4fc34be01d8a39f01cc17ef5"), "name": "Jacky", "Age": 23}
{"_id": ObjectId ("4fc34c1e1d8a39f01cc17ef6"), "name": "Tom", "addr": 23}
Where the age field of "Lily" is empty and Tom does not have an age field, we want to find the line with an age of NULL, as follows:

> Db.c2.find ({age:null})
{"_id": ObjectId ("4fc34bb81d8a39f01cc17ef4"), "name": "Lily", "Age": null}
{"_id": ObjectId ("4fc34c1e1d8a39f01cc17ef6"), "name": "Tom", "addr": 23}
Strangely enough, we thought we could only find "Lily," but "Tom" was also found, because "null" would not only match a document with a key value of NULL, but would also match a document that did not contain the key. So how can we only find "Lily"? We can use exists to limit it.


5: $mod modulo operation
Query age modulo 10 equals 0 of data

Db.student.find ({age: {$mod: [10, 1]}})

Examples are as follows:

The data for the C1 table is as follows:

Db.c1.find ()
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
Query age modulo 6 equals 1 of data

> Db.c1.find ({age: {$mod: [6, 1]}})
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
It can be seen that only the data of age modulo 6 equals 1 is shown, and other data that does not conform to the rules are not displayed.


6: $ne Not equal to
The value of the query x is not equal to 3 of the data

Db.things.find ({x: {$ne: 3}});

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
Query the value of age not equal to 7 of data

> Db.c1.find ({age: {$ne: 7}});
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
It can be seen that only data that is not equal to 7 is shown, and other data that does not conform to the rules are not displayed.


7: $in contains
Is the same as the purpose of SQL standard syntax, which is to query a range of enumerated values

Querying the value of x within the 2,4,6 range of data

Db.things.find ({x:{$in: [2,4,6]}});

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
Querying for the value of age within the 7,8 range of data

> Db.c1.find ({age:{$in: [7,8]}});
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
It can be seen that only data with age equal to 7 or 8 is shown, and other data that does not conform to the rules are not displayed.

The $in is flexible enough to specify different types of conditions and values.


8: $nin does not contain
Is the same as the purpose of SQL standard syntax, that is, the data to be queried is outside the range of a series of enumerated values

Querying the value of x outside the 2,4,6 range of data

Db.things.find ({x:{$nin: [2,4,6]}});

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
{"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": 30}
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
Querying for the value of age outside the range of 7,8 data

> Db.c1.find ({age:{$nin: [7,8]}});
{"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30}
It can be seen that only the age does not equal 7 or 8 of the data, other non-conforming data is not displayed


9: Number of $size array elements
For {name: ' David ', age:26, Favorite_number: [6, 7, 9]} record

Match Db.users.find ({favorite_number: {$size: 3}});

Mismatch Db.users.find ({favorite_number: {$size: 2}});

The "$size" is also useful for querying arrays, as the name implies, and it can be used to query for arrays of specific lengths. For example:

> Db.users.find ({favorite_number: {$size: 3}})
Getting a document within a length range is a common query. "$size" cannot be combined with other query conditions (such as "$GT"), but the query can be implemented by adding a "size" key to the document. This increments the value of "size" each time you add an element to the specified array. For example, the original update:

> db.users.update (criteria,{"$push": {"Favorite_number": "1"}})
It's going to turn out like this:

> Db.users.update (Criteria,
... {"$push": {"Favorite_number": "1"}, "$inc": {"$size": 1}})
The self-increment operation is very fast, so the impact on performance is minimal. Once the document is stored, you can query as follows:

> Db.users.find ({"$size": {"$GT": 3}})
Unfortunately, this technique cannot be used in conjunction with the "$addToSet" operator.


10: Regular Expression matching
Query mismatch name=b* lead record

Db.users.find ({name: {$not:/^b.*/}});

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ();
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}


11:javascript queries and $where queries
Query a more than 3 of the data, the following query method the same way

Db.c1.find ({A: {$gt: 3}});

Db.c1.find ({$where: "THIS.A > 3"});

Db.c1.find ("THIS.A > 3");

f = function () {return THIS.A > 3;} db.c1.find (f);


12:count query record number of lines
Count Query Record bars

Db.users.find (). Count ();

The following return is not 5, but the number of records in the user table

Db.users.find (). Skip (. Limit (5). Count ();

If you want to return the number of records after the limit, use count (true) or count (not 0)

Db.users.find (). Skip (. Limit (5). Count (True);

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
Querying the amount of data in a C1 table

> Db.c1.count ()
2
You can see that there are 2 data in the table



Two: Cursors
The 1:find command does not directly return the result, but instead returns an iterator to the result set, the cursor.

Like most database products, MongoDB also uses cursors to cycle through each result data, with the following syntax:

> for (var c = Db.t3.find (); C.hasnext ();) {
... Printjson (C.next ());
... }
{"_id": ObjectId ("4fb8e4838b2cb86417c9423a"), "Age": 1}
{"_id": ObjectId ("4fb8e4878b2cb86417c9423b"), "Age": 2}
{"_id": ObjectId ("4fb8e4898b2cb86417c9423c"), "Age": 3}
{"_id": ObjectId ("4fb8e48c8b2cb86417c9423d"), "Age": 4}
{"_id": ObjectId ("4fb8e48e8b2cb86417c9423e"), "Age": 5}

2:mongodb there is another way to handle cursors

> Db.t3.find (). ForEach (function (u) {printjson (U);});
{"_id": ObjectId ("4fb8e4838b2cb86417c9423a"), "Age": 1}
{"_id": ObjectId ("4fb8e4878b2cb86417c9423b"), "Age": 2}
{"_id": ObjectId ("4fb8e4898b2cb86417c9423c"), "Age": 3}
{"_id": ObjectId ("4fb8e48c8b2cb86417c9423d"), "Age": 4}

3:skip limit the starting point for returning records
Starting from 3rd record, return 5 records (limit 3, 5)

Db.users.find (). Skip (3). Limit (5);

Examples are as follows:

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}

4:sort sort
With age ascending ASC

Db.users.find (). Sort ({age:1});

Descending desc by age

Db.users.find (). Sort ({Age:-1});

The data for the C1 table is as follows:

> Db.c1.find ()
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
Query C1 table in ascending order of age

> Db.c1.find (). Sort ({age:1});
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
The 1th one is age=10, and then the result set is sorted in ascending order


Three: Stored Procedures

The stored procedure for a relational database is described as a set of SQL statements to complete a particular function, compiled and stored in a database, and executed by the user by specifying the name of the stored procedure and giving the parameter (if the stored procedure has parameters).

MongoDB offers a range of solutions for many problems, and it is not uncommon for other database features to remain weak. MongoDB also supports stored procedures, but MongoDB is written in JavaScript, which is the charm of MongoDB.


1:sql Custom Function conversion to MongoDB stored procedure
MongoDB also supports stored procedures. The first thing you need to know about stored procedures is that it's written in JavaScript. Maybe it makes you wonder why it's written in JavaScript, but it actually makes you very satisfied that the MongoDB stored procedure is stored in the Db.system.js table, and we imagine a simple SQL custom function like this:

function AddNumbers (x, y) {
return x + y;
}
Here we convert this SQL custom function to MongoDB's stored procedure:

> Db.system.js.save ({_id: "AddNumbers", Value:function (x, y) {return x + y;}});:

2: Querying Stored Procedures
Stored procedures can be viewed, modified, and deleted, so we use find to see if the stored procedure has been created.

> Db.system.js.find ()
{"_id": "AddNumbers", "value": Function cf__1__f_ (x, y) {
return x + y;
} }
>

3:eval function
The front looks pretty good, and here I look at the actual call to this stored procedure:

> Db.eval (' AddNumbers (3, 4.2) ');
7.2
>
This method of operation is simply too simple, perhaps this is the charm of MongoDB.

Db.eval () is a strange thing, and we can call the logic of the stored procedure directly inside and at the same time without having to declare the logic of the stored procedure beforehand.

> Db.eval (function () {return 3+3;});
6
>
As can be seen from the above, MongoDB stored procedures can easily complete the arithmetic operation, but other database products in the stored procedure can handle some things inside the database, such as the amount of data to take out a table and so on, these mongodb can do? The answer is yes, MongoDB can easily do, see the following example:

> Db.system.js.save ({_id: "get_count", Value:function () {return Db.c1.count ();}});
> Db.eval (' get_count () ')
2
You can see that stored procedures can easily manipulate tables in a stored procedure


Thanks for http://hubwiz.com/'s support.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Advanced query of MongoDB step one

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.