MongoDB's use Learning (vi) MONGODB advanced query condition operator

Source: Internet
Author: User
Tags mongodb query

This article is divided into two points, mainly in the 2nd--java syntax, but in order must first write the original ecological grammar

(There is also an article is good: MongoDB advanced query usage Daquan (including MongoDB command syntax and Java syntax, in fact, I organize this article ideal mode, AHA): http://www.cnblogs.com/t2xingzhe/p/3555268.html)

First, JavaScript syntax (original ecological grammar)

This section is reproduced from http://blog.csdn.net/u013339851/article/details/23600299

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 < value

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 all records that exist in the age field
Db.users.find ({age: {$exists: true}});
Query all records that do not exist in the name field
Db.users.find ({name: {$exists: false}});
Examples are as follows:
The data for the C1 table is as follows:
> Db.c1.find ();
{"_id": ObjectId ("4fb4a773afa87dc1bed9432d"), "age": +, "Length": 30}
{"_id": ObjectId ("4fb4a7e1afa87dc1bed9432e"), "age_1": +, "length_1": 30}
Querying for data that has field age
> Db.c1.find ({age:{$exists: true});
{"_id": ObjectId ("4fb4a773afa87dc1bed9432d"), "age": +, "Length": 30}
You can see that only the data with the age field is displayed, and the Age_1 data is not displayed.

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, so "null" could not only find itself, but even records that did not exist for the age field. So how can we only find "Lily"? We use exists to limit it:
> db.c2.find ({age:{"$in": [null], "$exists": True}})
{"_id": ObjectId ("4fc34bb81d8a39f01cc17ef4"), "name": "Lily", "Age": null}
So as we expected, only "Lily" was found out.

5, $mod modulo operation
    query age modulo 10 equals 0 data
    Db.student.find ({age: {$mod: [10 , 1]}})
    For example:
    C1 table data is as follows:
    > Db.c1.find ()
    {"_id" : ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": $
    {"_id": ObjectId ("4FB4AF89AFA87DC 1bed94331 ")," age ": 8," length_1 ": $
    {" _id ": ObjectId (" 4fb4af8cafa87dc1bed94332 ")," age ": 6," Len Gth_1 ": 6}
    query for age modulo 1 data
    > Db.c1.find ({age: {$mod: [6, 1]}})
  & nbsp {"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": 30}
    can see that only the data of age modulo 6 equals 1 is displayed, and other data that does not conform to the rules are not displayed

6, $ne not equal to
    Query x value is not equal to 3 data
    Db.things.find ({x: {$ne: 3}});
    Examples are as follows:
    C1 table data as follows:
    > Db.c1.find ()
    {"_id": ObjectId ("4f b4af85afa87dc1bed94330 ")," age ": 7," length_1 ": $
    {" _id ": ObjectId (" 4fb4af89afa87dc1bed94331 ")," a GE ": 8," length_1 ": $
    {" _id ": ObjectId (" 4fb4af8cafa87dc1bed94332 ")," age ": 6," length_1 ":}    Query The value of age is not equal to 7 data
    > Db.c1.find ({age: {$ne: 7}});
    {"_id": ObjectId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": $
    {"_id": Obje CtId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": $
    You can see that only the data of age equals 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 for a range of enumeration values within the scope of the query x values in the 2,4,6 range of data
    Db.things.find ({x:{$in: [2,4,6]}});
    Examples are as follows:
    C1 table data as follows:
    > Db.c1.find ()
    {"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": $
    {"_id": ObjectId ("4fb4af89afa87dc1bed94331") , "Age": 8, "length_1": $
    {"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30
    Query the value of age in the 7,8 range of data
    > Db.c1.find ({age:{$in: [7,8]}});
    {"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": $
    {"_id": Obje CtId ("4fb4af89afa87dc1bed94331"), "age": 8, "length_1": $
    You can see that only the data of age equals 7 or 8 is displayed, and other data that does not conform to the rules are not displayed /p>

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 scope of a series of enumeration values
    Querying the value of x in 2,4,6 Data outside the range
    db.things.find ({x:{$nin: [2,4,6]}});
    Examples are as follows:
    C1 table data as follows:
    > Db.c1.find ()
    {"_id": ObjectId ("4f b4af85afa87dc1bed94330 ")," age ": 7," length_1 ": $
    {" _id ": ObjectId (" 4fb4af89afa87dc1bed94331 ")," a GE ": 8," length_1 ": $
    {" _id ": ObjectId (" 4fb4af8cafa87dc1bed94332 ")," age ": 6," length_1 ":}    Query the value of age outside the 7,8 range of data
    > Db.c1.find ({age:{$nin: [7,8]}});
    {"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": +
    You can see that only the age does not Data equal to 7 or 8, other data that does not conform to the rules are not displayed

9, $size number of array elements
    for {name: ' David ', age:26, Favorite_number: [6, 7, 9]} Records
  & nbsp Match Db.users.find ({favorite_number: {$size: 3}});
    mismatch Db.users.find ({favorite_number: {$size: 2}});
    Examples are as follows:
    C1 table data as follows:
    > Db.c1.find ()
    {"_id": ObjectId ("4fb4af85afa87dc1bed94330"), "age": 7, "length_1": $
    {"_id": ObjectId ("4fb4af89afa87dc1bed94331") , "Age": 8, "length_1": $
    {"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": 30
    Query The age value for data outside the 7,8 range
    > Db.c1.find ({age:{$nin: [7,8]}});
    {"_id": ObjectId ("4fb4af8cafa87dc1bed94332"), "age": 6, "length_1": +
    You can see that only the age does not Data equal to 7 or 8, other data that does not conform to the rules are not displayed

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}
Query for data whose name does not start with T
> Db.c1.find ({name: {$not:/^t.*/}});
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
It can be seen that only the Name=tony data is displayed, and other non-conforming data is not displayed.

11. JavaScript Query and $where query
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 bar number
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

13. Skip limit Returns the starting point of the record
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}
Querying the 2nd data of the C1 table
> Db.c1.find (). Skip (1). Limit (1)
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
You can see that the 2nd piece of data in the table is displayed.

14. Sort order
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
Query C1 table sorted in descending order of age
> Db.c1.find (). Sort ({Age:-1});
{"_id": ObjectId ("4fb5faaf6d0f9d8ea3fc91a8"), "name": "Tony", "Age": 20}
{"_id": ObjectId ("4fb5fab96d0f9d8ea3fc91a9"), "name": "Joe", "Age": 10}
The 1th one is age=20, and then the result set is sorted in descending order

Second,Java syntax (Spring data syntax)

@Test Public voidquerylist () {query Query=NewQuery (); Query.addcriteria (Criteria.where ("Level"). GTE (4). LT (12));//Level >= 4 and Level <Query.addcriteria (Criteria.where ("Ckey"). Is ("145"));//Ckey = 145Query.addcriteria (Criteria.where ("area"). Regex ("^1024"));//Area like ' 1024% 'Query.with (NewSort (NewSort.order (Sort.Direction.DESC, "ptime"));//ORDER BY ptime Descpagination<news> page = newsservice.getpagearticle (1, 10, query);        System.out.println (Page.gettotalcount ()); if(Page! =NULL&& Page.getdatas ()! =NULL&& Page.getdatas (). Size () > 0) {             for(News A:page.getdatas ()) {System.out.println (A.getid ()+ "-" + a.getlevel () + "-" + a.getarea () + "-" +a.gettitle ()); }        }    }

The MONGODB query statement executed is: {"level": {"$gte": 4, "$lt": "Ckey", "145", "area": {"$regex": "^1024"}}, Fields:null, S ORT: {"Ptime":-1}

Can be seen, spring data syntax more natural, more in line with our people's thinking, more in line with the code of the program ape habits, not, haha, spring data is strong, really want to monopolize the Java aspect of all things ah, very scary appearance, first not discuss this, rookie some use on the line, Who is convenient to use?

This is my own test of the code, not every operator has tested the past, there is time to say again, the project source will be released, for everyone to shoot bricks ...

Still, on the road ...

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.