How do you start learning a new database? When you can add, delete, change, and look up a database, you can say that this database is an entry, if you need to go further, you need to understand the characteristics of the database, such as indexes, things, locks, distributed support, etc

This blog post is an introduction to mongodb. It will show you some basic query operations and how you can play with them in Spring

The original article can see: 190113-SpringBoot advanced MongoDB query basic posture

I. Basic use

0. Prepare the environment

Before you get started, prepare the environment and set up the project. For more information on this step, see the blog post 181213-SpringBoot Advanced MongoDB Setup and Use

Next, in a collection, prepare the following data, which is our basic query scope

1. Query information by field

The most common Query scenario, such as when we Query the data for user= a grey blog, is mainly done with Query + Criteria

@Component
public class MongoReadWrapper {
    private static final String COLLECTION_NAME = "demo";

    @Autowired
    private MongoTemplate mongoTemplate;

    /** * Specifies field query */
    public void specialFieldQuery(a) {
        Query query = new Query(Criteria.where("user").is("A Gray Blog"));
        // Query a piece of data that meets the criteria
        Map result = mongoTemplate.findOne(query, Map.class, COLLECTION_NAME);
        System.out.println("query: " + query + " | specialFieldQueryOne: " + result);

        // Data that satisfies all conditions
        List<Map> ans = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
        System.out.println("query: " + query + " | specialFieldQueryAll: "+ ans); }}Copy the code

Select * from case where case = case where case = case

  • Criteria.where(xxx).is(xxx)To specify specific query conditions
  • Encapsulating Query Objectsnew Query(criteria)
  • With the help ofmongoTemplateExecute the querymongoTemplate.findOne(query, resultType, collectionName)

FindOne indicates that only one data meeting the condition is obtained. Find returns all that meet the criteria; After the above execution, the delete result is as follows

The query: query: {" user ", "a dusty blog"}, Fields: {}, Sort: {} | specialFieldQueryOne: {_id = 5 c2368b258f984a4fda63cee, blog user = one is gray, desc = handsome aggressive yards farming community old show} the query: query: {" user ":" a dusty blog "}, Fields: {}, Sort: { } | specialFieldQueryAll: [{_id = 5 c2368b258f984a4fda63cee, blog user = one is gray, desc = handsome aggressive yards farming community old show}, {_id = 5 c3afaf4e3ac8e8d2d39238a, blog user = one is gray, Desc = handsome aggressive yards farming community old show 3}, {_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 20.0}, {_id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, Desc = 0, sign= 0, sign= 0}]Copy the code

2. And Query multiple conditions

Front is only one condition is met, now if it is a requirement to satisfy multiple conditions at the same time, with org. Springframework. Data. The mongo. Core. Query. Criteria# and diagonal to multiple queries

/** * Multiple query conditions are met */
public void andQuery(a) {
    Query query = new Query(Criteria.where("user").is("A Gray Blog").and("age").is(18));
    Map result = mongoTemplate.findOne(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | andQuery: " + result);
}
Copy the code

The deletion result is as follows

The query: query: {" user ":" a dusty blog ", "age" : 18}, Fields: {}, Sort: {} | andQuery: {_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}Copy the code

3. Or query

, and the corresponding is or just need a meet in multiple conditions, the use of the and the and some differences, with the aid of org. Springframework. Data. The mongo. Core. Query. Criteria# orOperator, The passed arguments are multiple Criteria objects, each of which represents a query condition

/** * or query */
public void orQuery(a) {
    / / equivalent to the getCollection (' demo '). The find ({" user ":" blog "one is gray, $or: [{" age" : 18}, {" sign ": {$exists: true}}]})
    Query query = new Query(Criteria.where("user").is("A Gray Blog")
            .orOperator(Criteria.where("age").is(18), Criteria.where("sign").exists(true)));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | orQuery: " + result);

    // A separate or query
    / / equivalent to Query: {$" or ": [{" age" : 18}, {" sign ": {" $exists" : true}}]}, Fields: Sort: {} {},
    query = new Query(new Criteria().orOperator(Criteria.where("age").is(18), Criteria.where("sign").exists(true)));
    result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | orQuery: " + result);
}
Copy the code

The command output is

The query: query: {" user ":" a dusty blog ", "$or" : [{" age ": 18}, {" sign" : {" $exists ": true}}]}, Fields: {}, Sort: { } | orQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, Query: query: {"$or" : [{"age" : 18}, {"sign" : {"$exists" : true } }] }, Fields: { }, Sort: { } | orQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, Desc = 6 handsome aggressive yards farming community old show, and sign = hello world}, {_id = 5 c3b0538e3ac8e8d2d392390, blog user = 2 is gray, desc = 6 handsome aggressive yards farming community old show, and sign = hello world}]Copy the code

4. In the query

The standard in query case

/** * in query */
public void inQuery(a) {
    // Equivalent to:
    Query query = new Query(Criteria.where("age").in(Arrays.asList(18.20.30)));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | inQuery: " + result);
}
Copy the code

The output

query: Query: { "age" : { "$in" : [18, 20, 30] } }, Fields: { }, Sort: { } | inQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, 7, age=20.0}]Copy the code

5. Numerical comparison

Value comparison size, mainly using get, gt, lt, let

/** * Number type, compare query > */
public void compareBigQuery(a) {
    // age > 18
    Query query = new Query(Criteria.where("age").gt(18));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | compareBigQuery: " + result);

    // age >= 18
    query = new Query(Criteria.where("age").gte(18));
    result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | compareBigQuery: " + result);
}

/** * Number type, compare query < */
public void compareSmallQuery(a) {
    // age < 20
    Query query = new Query(Criteria.where("age").lt(20));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | compareSmallQuery: " + result);

    // age <= 20
    query = new Query(Criteria.where("age").lte(20));
    result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | compareSmallQuery: " + result);
}
Copy the code

The output

query: Query: { "age" : { "$gt" : 18 } }, Fields: { }, Sort: { } | compareBigQuery: [{_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 20.0}] the query: query: {" age ": {" $gte" : 18 } }, Fields: { }, Sort: { } | compareBigQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, Desc = 6 handsome aggressive yards farming community old show, and the age = 20.0}] the query: query: {" age ": {" $lt: 20}}, Fields: {}, Sort: {} | compareSmallQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}] the query: query: {" age ": {" $lte" : 20 } }, Fields: { }, Sort: { } | compareSmallQuery: [{_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, 7, age=20.0}]Copy the code

6. Regular query

Excellent function

/** * Regular query */
public void regexQuery(a) {
    Query query = new Query(Criteria.where("user").regex("^ a Gray Blog"));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | regexQuery: " + result);
}
Copy the code

The output

Query: the query: {" user ": {" $regex" : "^ a dusty blog", "$options" : ""}}, Fields: {}, Sort: {} | regexQuery: [{_id = 5 c2368b258f984a4fda63cee, blog user = one is gray, desc = handsome aggressive yards farming community old show}, {blog2 _id = 5 c3afacde3ac8e8d2d392389, user = one is gray, Desc = handsome aggressive yards farming community old show 2}, {_id = 5 c3afaf4e3ac8e8d2d39238a, blog user = one is gray, desc = handsome aggressive yards farming community old show 3}, {_id = 5 c3afafbe3ac8e8d2d39238b, Blog4 user = one is gray, desc = handsome aggressive yards farming community old show 4}, {blog5 _id = 5 c3afb0ae3ac8e8d2d39238c, user = one is gray, desc = handsome aggressive yards farming community old show 5}, {_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, Desc = 6 handsome aggressive yards farming community old show, and the age = 20.0}, {_id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and sign = hello world}]Copy the code

7. Query the total number

Mongotemplate-count is the key method to use for statistics

/** * Total number of queries */
public void countQuery(a) {
    Query query = new Query(Criteria.where("user").is("A Gray Blog"));
    long cnt = mongoTemplate.count(query, COLLECTION_NAME);
    System.out.println("query: " + query + " | cnt " + cnt);
}
Copy the code

The output

The query: query: {" user ", "a dusty blog"}, Fields: {}, Sort: {} | CNT 5Copy the code

8. Group query

So this corresponds to a group query in mysql, but in mongodb, it’s more of an aggregate query, and you can do a lot of things like that, so let’s look at how do we do group totals

/* * Group query */
public void groupQuery(a) {
    // Count the number of groups by user name
    // aggregate([ { "$group" : { "_id" : "user" , "userCount" : { "$sum" : 1}}}] )
    Aggregation aggregation = Aggregation.newAggregation(Aggregation.group("user").count().as("userCount"));
    AggregationResults<Map> ans = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
    System.out.println("query: " + aggregation + " | groupQuery " + ans.getMappedResults());
}
Copy the code

Notice that we use Aggregation instead of Query and Criteria, and the output looks like this

query: { "aggregate" : "__collection__", "pipeline" : [{ "$group" : { "_id" : "$user", "userCount" : { "$sum" : [{1}}}}] | groupQuery _id = a dusty blog, userCount = 5}, {blog2 _id = one is gray, userCount = 1}, {blog4 _id = one is gray, userCount = 1}, {_id= blog5, userCount=1}, {_id= blog5, userCount=1}]Copy the code

9. The sorting

Sort is more common, and one of the things that’s interesting in mongodb is that certain fields don’t necessarily exist in document, what about that?

/** * Sort queries */
public void sortQuery(a) {
    // sort Specifies the query condition
    Query query = Query.query(Criteria.where("user").is("A Gray Blog")).with(Sort.by("age"));
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | sortQuery " + result);
}
Copy the code

The output is as follows, and the document without this field is also found

Query: query: {"user" : "a blog"}, Fields: {}, Sort: {"age" : [{1} | sortQuery _id = 5 c2368b258f984a4fda63cee, blog user = one is gray, desc = handsome aggressive yards farming community old show}, {_id = 5 c3afaf4e3ac8e8d2d39238a, Blog user = one is gray, desc = handsome aggressive yards farming community old show 3}, {_id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and sign = hello world}, {_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, 7, age=20.0}]Copy the code

10. Paging

When the amount of data is large, paging query is more common, and limit and SKIP are often used

/** * Paging query */
public void pageQuery(a) {
    // limit Specifies that two items are to be queried
    Query query = Query.query(Criteria.where("user").is("A Gray Blog")).with(Sort.by("age")).limit(2);
    List<Map> result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | limitPageQuery " + result);


    // Skip () method to skip a specified amount of data
    query = Query.query(Criteria.where("user").is("A Gray Blog")).with(Sort.by("age")).skip(2);
    result = mongoTemplate.find(query, Map.class, COLLECTION_NAME);
    System.out.println("query: " + query + " | skipPageQuery " + result);
}
Copy the code

The output shows that limit is used to limit how many pieces of data to query, and skip means how many pieces of data to skip

Query: query: {"user" : "a blog"}, Fields: {}, Sort: {"age" : [{1} | limitPageQuery _id = 5 c2368b258f984a4fda63cee, blog user = one is gray, desc = handsome aggressive yards farming community old show}, {_id = 5 c3afaf4e3ac8e8d2d39238a, User = 0, desc= 0}] query: query: {"user" : "user"}, Fields: {}, Sort: {"age" : [{1} | skipPageQuery _id = 5 c3b003ee3ac8e8d2d39238f, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and sign = hello world}, {_id = 5 c3afb1ce3ac8e8d2d39238d, blog user = one is gray, desc = 6 handsome aggressive yards farming community old show, and the age = 18.0}, {_id = 5 c3b0031e3ac8e8d2d39238e, blog user = one is gray, 7, age=20.0}]Copy the code

11. A summary

What if we need to query some fields in a Document? For example, if the document internal results are more complex, how can we play with nested queries when there are nested objects or arrays? Index what can be used to optimize query efficiency? How do I get the timestamp of document creation from the supposedly auto-generated _ID?

Leave those questions open and fill them in later

II. The other

0. Project

  • Engineering: the spring – the boot – demo

  • module: mongo-template

  • Related blog: 181213-SpringBoot advanced MongoDB basic environment construction and use

1. A gray Blog

  • A gray Blog personal Blog blog.hhui. Top
  • A Gray Blog-Spring feature Blog Spring.hhui. Top

A gray personal blog, record all study and work in the blog, welcome everyone to visit

2. Statement

The above content is not as good as the letter, purely the words of a family, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro-blog address: small gray Blog
  • QQ: A gray /3302797840

3. Scan for attention

A gray blog

Knowledge of the planet