MongoDB database java configuration

Posted by weekenthe9 on Thu, 20 Jan 2022 18:15:44 +0100

MongoDB

RDBMS vs NoSQL

RDBMS
-Highly organized structured data
-Structured query language (SQL)
-Data and relationships are stored in separate tables.
-Data manipulation language
-Strict consistency
-Basic transaction

NoSQL
-Represents more than just SQL
-No declarative query language
-There are no predefined patterns

  • Key value pair storage, column storage, document storage, graphics database
    -Final consistency, not ACID attribute
    -Unstructured and unpredictable data
    -CAP theorem
    -High performance, high availability and scalability

Document oriented storage

  • Features: document database stores data in the form of document, similar to JSON. It is a collection of a series of data items. Each data item has a name and

    The corresponding value can be a simple data type, such as string, number, date, etc; It can also be complex types, such as sequence tables and associated objects.

  • Advantages: the data structure requirements are not strict, the table structure is variable, and the table structure does not need to be defined in advance like the relational database.

  • Disadvantages: low query performance and lack of unified query syntax.

  • Application scenario: log, Web application, etc.

  • NoSQL representatives: MongoDB, CouchDB

Characteristics and applicable scenarios of MongoDB

practicability

MongoDB is a document oriented database. It is not a relational database. It directly accesses BSON, which means that MongoDB is more flexible because it can directly insert complex data types such as arrays into documents, and the key and value of documents are not fixed data types and sizes, Therefore, when using MongoDB, developers do not need to predefine database objects such as "tables" in the relational database. Designing the database will become very convenient and can greatly improve the development progress.

Availability and load balancing

MongoDB's implementation of high availability and read load balancing is very simple and friendly. MongoDB comes with the concept of replica set. By designing replica set and driver suitable for its own business, it can effectively and conveniently realize high availability and read load balancing. In other database products, if you want to realize the above functions, you often need to install additional complex middleware, which greatly improves the system complexity, troubleshooting difficulty and operation and maintenance cost.

Expansibility

In terms of scalability, assuming that the application data grows very rapidly, it is often unrealistic and manual to continuously add disk capacity and memory capacity Sub database and sub table It will also bring very heavy workload and technical complexity. In terms of scalability, MongoDB has a very effective and ready-made solution. Through its own Mongos cluster , you can realize automatic horizontal expansion and routing of program segments by adding Mongo fragments at an appropriate time. On the one hand, it can alleviate the reading and writing pressure of a single node, and on the other hand, it can effectively balance the use of disk capacity. The whole mongos cluster is completely transparent to the application layer, and can perfectly achieve the high availability of various mongos cluster components.

data compression

Since the launch of MongoDB 3.0, MongoDB has introduced a high-performance storage engine WiredTiger, and its data compression performance has been greatly improved. Compared with the previous MMAP engine, the compression ratio can be increased by at least 5 times, which can greatly improve the utilization of disk space.

Other features

Compared with other relational databases, MongoDB introduces the concept of "fixed set". The so-called fixed set means that the size of the whole set is pre-defined and fixed, and the interior is one Circular queue , if the collection is full, the MongoDB background will automatically clean up the old data, and since the fixed space is written every time, the write speed can be greatly improved. This feature is very suitable for log applications. There is no need to worry about the crazy growth of log cleaning measures and write efficiency. In addition, more detailed elimination policy settings are required. You can also use TTL index (time to live index), that is, the index with life cycle, which allows you to set an expiration time for each record. When a record meets its setting conditions, it can be automatically deleted.

Comparison of basic terms

sql terminology and conceptsMongoDB terminology and concepts
databasedatabase
tablecollection
rowdocument or BSON document
columnfield
indexindex
table joinsembedded document and linking
primary key Specify any unique column or column combination as primary key. (specify any unique column or combination of columns as the primary key)primary keyIn MongoDB, the primary key isautomatically set to the _id fifield. (in mongodb, the primary key is automatically set to the _idfield)
aggregation (e.g. group by)MongoDB provides three ways to perform aggregation: the aggregation pipeline, the map-reduce function, and single purpose aggregation methods. (aggregate operation)

MongoDB data type

data typedescribe
Stringcharacter string. The type of data commonly used to store data. In MongoDB, UTF-8 encoded string is legal
IntegerInteger value. Used to store values. According to the server you use, it can be divided into 32-bit or 64 bit
BooleanBoolean value. Used to store Boolean values (true / false)
DoubleDouble precision floating point value. Used to store floating point values
Min/Max keysCompare a value with the lowest and highest values of the BSON (binary JSON) element
ArraysUsed to store an array or list or multiple values as a key.
TimestampTimestamp. Record the specific time when the document is modified or added
ObjectFor embedded documents
NullUsed to create null values
SymbolSymbol. This data type is basically equivalent to the string type, but the difference is that it is generally used for languages with special symbol types
DateDate and time. Use the UNIX time format to store the current date or time. You can specify your own date and time: create a date object and pass in the year, month and day information
Object IDObject ID. ID used to create the document
Binary DataBinary data. Used to store binary data
CodeCode type. Used to store JavaScript code in a document
Regular expressionRegular expression type. Used to store regular expressions

Common permissions

jurisdictionexplain
readAllows the user to read the specified database
readWriteAllows users to read and write to the specified database
userAdminAllow users to send messages to system The users collection is written, and users can be created, deleted and managed in the specified database
dbAdminAllows users to perform management functions in the specified database, such as index creation, deletion, viewing statistics or accessing system profifile
clusterAdminIt must be defined in the admin database to give the user administrative rights for all partition and replica set related functions.
readAnyDatabaseIt must be defined in the admin database to give users read permission to all databases.
readWriteAnyDatabaseIt must be defined in the admin database to give users read and write permissions to all databases
userAdminAnyDatabaseIt must be defined in the admin database to give users userAdmin permission for all databases
dbAdminAnyDatabaseIt must be defined in the admin database to give users dbAdmin permission for all databases
rootSuper account and super permission must be defined in admin database.

Create user

  • User: user name
  • pwd: password
  • customData: stores user-defined data related to users. This attribute can also be ignored
  • roles: array type to configure user permissions
  • db: valid database
db.createUser({user:"uaad",pwd:"uaad",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})

Modify mongod CFG configuration file

#security:
security:
  #Turn on user authority authentication
  authorization: enabled
  • Restart mongodb database

    net stop mongodb
    net start mongodb
    net start nongodb --auth
    

Database operation

  • Switch or create database: use database name (switch if the database exists and create if it does not exist. Note that if there is no data in the database, it will not be displayed)
  • Display database: show dbs (display all databases) db (display the current database)
  • Delete database (permission required): dB dropDatabase()

Operation of collection

  • Create collection: dB Createcollection (name, options), name: the name of the collection to be created. Options: optional parameter that specifies options for memory size and index.

  • When creating documents in MongoDB, the collection will be created automatically, unless you have special requirements for the created collection.

    # Mode 1:
    db.c2.insert({"a":1}) # When the first document is inserted, the collection is created and contains the document
    # Mode 2:
    db.c3 # Create an empty collection. If there is no data in it, you can't view it through show tables or show collections. Need to add to the collection
     Insert a document into the to see it
    
fieldtypedescribe
cappedBoolean(optional) if true, a fixed collection is created. A fixed set is a set with a fixed size. When the maximum value is reached, it will automatically overwrite the oldest document. When the value is true, the size parameter must be specified.
sizenumerical value(optional) limit the size of the collection space. The default is no limit (in bytes). This field must be specified if capped is true.
autoIndexIdBoolean(optional) if it is true, it is automatically displayed in the_ The id field creates an index. The default is true.
maxnumerical value(optional) limit the maximum number of documents in the collection. The default is no limit.
  • View Collections: show tables or show collections
  • Pass db Set name stats() to view the collection details.
  • Delete collection: db Set name drop()

Document operation

  • Single insert: db Collection name insert(document name), if not specified when inserting a document_ id is the ObjectId type by default_ id cannot be repeated and cannot be changed after insertion.

    1. db.c1.insert({"name":"a"})
    2. db.c1.insertOne({"name":"a"})
    3. db.c1.save({"name":"a"})
    user1 = { 
     "name":"zhangsan", 
     "age":18, 
     "hobbies":["music", "read"], 
     "addr":{ 
     "country":"China", 
     "city":"BJ" 
     } 
    } 
    db.user.insert(user1)
    
  • Batch insert:

    1. db. Collection name insert([{name:“a”}, {name:“b”}])

    2. db. Collection name insertMany([{name:“a”}, {name:“b”}])

    3. db. Collection name save([{name:“a”}, {name:“b”}])

    4. user1 = { 
       "_id":1, 
       "name":"zhangsan", 
       "age":1, 
       "hobbies":["music", "read"], 
       "addr":{ 
       "country":"China", 
       "city":"BJ" 
       } 
      } 
      user2 = { 
       "_id":2, 
       "name":"lisi", 
       "age":2, 
       "hobbies":["music", "read"], 
       "addr":{ 
       "country":"China", 
       "city":"SH" 
       } 
      } 
      user3 = { 
       "_id":3, 
       "name":"wangwu", 
       "age":3, 
       "hobbies":["music", "read"], 
       "addr":{ 
       "country":"China", 
       "city":"GZ" 
       } 
      } 
      user4 = { 
       "_id":4, 
       "name":"zhaoliu", 
       "age":4, 
       "hobbies":["music", "read"], 
       "addr":{ 
       "country":"China", 
       "city":"SZ" 
       } 
      } 
      user5 = { 
       "_id":5, 
       "name":"tianqi", 
       "age":5, 
       "hobbies":["music", "read"], 
       "addr":{ 
       "country":"China", 
       "city":"TY" 
       }
      } 
      db.user.insert([user1, user2, user3, user4, user5])
      
  • Update document: db Set name update(query, update, options)

    • Query: query condition of update, similar to where in SQL update statement.
    • Update: update object and some Update Operators (such as s e t , set, Set, inc...) can also be understood as the set part of the SQL update statement.
    • upsert: optional. If there is no update document, whether to insert it. true is insert. The default is false. No insert.
    • multi: optional, whether to update in batch. true means that the multiple records queried by the criteria are all updated. False only updates the first record found. The default is false.
  • Note: updating a document is the operation of updating the whole document. If the modified values are only name and age, except_ Attributes other than id will be deleted.

user = { 
 "name":"wangwu", 
 "age":20, 
 "hobbies":["music", "read"], 
 "addr":{ 
 "country":"China", 
 "city":"BJ" 
 } 
} 
# Modify single article
db.user.updateOne({"name":"lisi"}, {"$set": user}) 
# If there are multiple matching data found, only the first one will be modified
db.user.update({"name":"lisi"}, user) # Modifying a single entry is equivalent to updateOne() 
# If there are multiple matching data found, modify all matching records
db.user.update({"name":"lisi"}, {"$set": user}, false, true) # Modify multiple
db.user.updateMany({"name":"Zhang San 123123"}, {"$set": user}) # Modify multiple

Update Operators

  • db. Set name update({query}, {update operator: {update})

    1. Query: query condition of update, similar to where in SQL update statement.

    2. Update: update object and some Update Operators (such as s e t , set, Set, inc...) can also be understood as set in SQL update statement

      part.

  • Common operators

    Operatoreffect
    $setIt is used to specify a key and update the key value. If the key does not exist, it is created.
    $incYou can increase or decrease a key whose value is numeric (only the number that meets the requirements).
    $unsetIt is mainly used to delete keys.
    $pushAdd an array element to the key of an array type of the document without filtering duplicate data. When adding, the key exists, and the key value type must be array; If the key does not exist, create a key of array type.
    $popDelete data element. 1 means to delete from the tail of the array, - 1 means to delete elements from the head of the array.
    $pullDelete the elements that meet the criteria from the array.
    $pullAllDelete multiple elements that meet the criteria from the array.
    $renameRename the key.

remove document

  • db. Collection name remove(, {justOne: })

    1. query: (optional) the condition of the deleted document.
    2. justOne: (optional) if set to true, only one document will be deleted, and False will delete all matching data
    #Delete the first document that meets the criteria
    db.user.deleteOne(<query>) 
    #Delete all data command
    db.user.remove({}) 
    #Clearing the set (table) is equivalent to the previous one
    db.user.deleteMany({})
    

consult your documentation

# Equivalent to DB user. find({}) 
db.user.find() 
# duplicate removal
db.user.distinct('name')

The find() method displays all documents in an unstructured manner. If you need to read data in a readable way, you can use the pretty() method. The syntax format is as follows:

# The pretty() method displays all documents in a formatted manner
db.user.find().pretty()

operation

compare
#1,select * from user where id = 3 
db.user.find({"_id":3}) 
#2,select * from user where id != 3 
db.user.find({"_id":{"$ne":3}}) 
#3,select * from user where id > 3 
db.user.find({"_id":{"$gt":3}}) 
#4,select * from user where age < 3 
db.user.find({"age":{"$lt":3}}) 
#5,select * from user where id >= 3 
db.user.find({"_id":{"$gte":3}}) 
#6,select * from user where id <= 3 
db.user.find({"_id":{"$lte":3}})
logic
  • In MongoDB, multiple conditions in the dictionary are separated by commas, which are and relationships, or directly use $and, $or, $not (and or not)
#Logical operation: $and,$or,$not 
#1 select * from user where id >=3 and id <=4; 
db.user.find({"_id":{"$gte":3,"$lte":4}}) 
#2 select * from user where id >=3 and id <=4 and age >=4; 
db.user.find({ 
 "_id":{"$gte":3,"$lte":4}, 
 "age":{"$gte":4} 
}) 
db.user.find({ 
 "$and": [ 
 {"_id": {"$gte":3, "$lte":4}}, 
 {"age": {"$gte":4}} 
 ] 
}) 
#3 select * from user where id >=0 and id <=1 or id >=4 or name = "tianqi"; 
db.user.find({ 
 $or: [ 
 {"_id": {$gte:0, $lte:1}}, 
 {"_id": {$lte:4}}, 
 {"name": "tianqi"} 
 ] 
}) 
db.user.find({ 
 "$or": [ 
 {"$and": [ 
 {"_id": {"$gte": 0}}, 
 {"_id": {"$lte": 1}} 
 ]}, 
 {"_id": {"$gte": 4}}, 
 {"name": "tianqi"} 
 ] 
}); 
#4 select * from user where id % 2 = 1; 
db.user.find({"_id":{"$mod":[2,1]}}) 
#Reverse the previous one
db.user.find({ 
 "_id":{"$not":{"$mod":[2,1]}} 
})
member
  • Member operations are nothing but in and not in. The form in MongoDB is $in, $nin
#1,select * from user where age in (1,2,3); 
db.user.find({"age":{"$in":[1,2,3]}}) 
#2,select * from user where name not in ("zhangsan","lisi"); 
db.user.find({"name":{"$nin":["zhangsan","lisi"]}})
$type
  • The types that can be used in MongoDB are shown in the following table:

    typenumberremarks
    Double1
    String2
    Object3
    Array4
    Binary data5
    Undefined6Obsolete.
    Object id7
    Boolean8
    Date9
    Null10
    Regular Expression11
    javaScript13
    Symbol14
    JavaScript(with scope)15
    32-bit integer16
    TimeStamp17
    64-bit integer18
    Min key255Query with -1
    Max key127
  • #Query name is data of string type

    db.user.find({name:{$type:2}}) 
    
regular
  • Regular defined in / /

    #1,select * from user where name regexp '^z.*?(n|u)$'; 
    #Matching rule: start with z, end with n or u, case insensitive
    db.user.find({'name':/^z.*?(n|u)$/i})
    
Projection
  • MongoDB projection means to select only the necessary data rather than the data of an entire file.

  • In MongoDB, when the find() method is executed, it will display all the fields of a document. To limit this, you need to set the field list value 1 or 0. 1 is used to display fields and 0 is used to hide fields_ id will be displayed by default

    #1,select name,age from user where id=3; 
    db.user.find({'_id':3},{'_id':0,'name':1,'age':1}) 
    #2,select name,age from user where name regexp "^z.*(n|u)$"; 
    db.user.find({ 
     "name":/^z.*(n|u)$/i 
    }, 
    { 
     "_id":0, 
     "name":1, 
     "age":1 
    } 
    )
    
array
#Query array correlation
#Check for dancing in hobbies
db.user.find({ 
 "hobbies":"dancing" 
}) 
#See people who have both dancing and tea hobbies
db.user.find({ 
 "hobbies":{"$all":["dancing","tea"]} 
}) 
#View the second person whose hobby is dancing in the index (the index starts from 0) 
db.user.find({ 
 "hobbies.2":"dancing" 
})
#View everyone's first to second hobbies. The first {} indicates that the query criteria are all, and the second is the display criteria (closed on the left and open on the right) 
db.user.find( 
{}, 
{ 
 "_id":0, 
 "name":0, 
 "age":0, 
 "addr":0, 
 "hobbies":{"$slice":[0,2]}, 
} 
) 
#View the last two hobbies of everyone. The first {} indicates that the query criteria are all, and the second is the display criteria
db.user.find( 
{}, 
{ 
 "_id":0, 
 "name":0, 
 "age":0, 
 "addr":0, 
 "hobbies":{"$slice":-2}, 
} 
) 
#Query the person with "country":"China" in the subdocument
db.user.find( 
{ 
 "addr.country":"China" 
} 
)
sort
  • In MongoDB, use the sort() method to sort the data. The sort() method can specify the fields to be sorted through parameters, and use 1 and - 1 to specify the sorting method, where 1 is ascending and - 1 is descending.

    # By name
    db.user.find().sort({"name":1}) 
    # Reverse by age, positive by id
    db.user.find().sort({"age":-1,'_id':1})
    
paging
  • limit indicates how many documents are taken, skip indicates how many documents are skipped, and the paging formula is as follows:

    db.user.find().skip((pageNum–1)*pageSize).limit(pageSize)
    
    db.user.find().limit(2).skip(0) # First two
    db.user.find().limit(2).skip(2) # Third and fourth
    db.user.find().limit(2).skip(4) # Fifth and sixth
    
Statistics
# Inquiry_ Number of people with id greater than 3
# Mode 1
db.user.count({'_id':{"$gt":3}}) 
# Mode II
db.user.find({_id:{"$gt":3}}).count()

Configure Mongodb for SpringBoot

Import spring data mongodb dependency

<!-- spring data mongodb rely on -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

application. Configure mongodb in YML file

spring:
 data:
    # mongodb configuration
   mongodb:
      # server address
     host: 127.0.0.1
      # port
     port: 27017
      # user name
     username: uaad
      # password
     password: hanyiming
      # Authentication database
     authentication-database: admin
      # Operational database
     database: test

Defines the class that responds to the mongodb database document

/**
 * Declare a java class as a mongodb document. You can specify the document corresponding to this class through the collection parameter
 * It can be omitted. If omitted, the lower case mapping set of class name will be used by default
 * If @ Document is not added, save to people
 * If @ Document is added, save to collection1
 */
@Data
public class People implements Serializable{
//    @Indexed: declare that the field needs an index. Indexing can greatly improve query efficiency.
//    @Compound index: the declaration of composite index. Building a composite index can effectively improve the query efficiency of multiple fields
    //Primary key identification. The value of this attribute will automatically correspond to the primary key field "_id" of mongodb. If the attribute name is "Id", the annotation can be omitted, otherwise it must be written
    @Id
    private String id;
    //This attribute corresponds to the field name of mongodb. If it is consistent, this annotation is not required
    @Field("name")
    private String name;
    private int age;

}

Syntax for specific operation of mongodb database

@Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PeopleRepository peopleRepository;

    /**
     * Insert document
     */
    @Test
    public void insert() {
        People people = new People();
        people.setAge(15);
        people.setName("Li Si");
        People insert = mongoTemplate.insert(people);
        System.out.println(insert);
    }

    /**
     * Update document
     */
    @Test
    public void update() {
        People people = new People();
        people.setId("61e7b43790ea156906d8741e");
        people.setAge(15);
        people.setName("Update test");
        //When using save, if the id does not exist, it is added, and if the id exists, it is modified
        //Note that if the update operation field is empty, the fields in the database will be deleted automatically
        People save = mongoTemplate.save(people);
        System.out.println(save);
    }


    /**
     * updateFirst
     * Modify the first qualified data
     */
    @Test
    public void updateFirst() {
        // Set query body and specific content of query criteria
        Criteria criteria = Criteria.where("name").is("Li Si");
        // Query set query criteria
        Query query = new Query(criteria);
        // Set which properties to modify
        Update update = new Update();
        update.set("name", "Li si123");
        // People.class tells Spring Data MongoDB which class the above attribute is.
        // Class corresponds to the collection, and you know which property of the specific operation collection
        UpdateResult result = mongoTemplate.updateFirst(query, update, People.class);
        // If the modified quantity is the same before and after modification, 0 will be returned
        System.out.println(result.getModifiedCount());
        // Match quantity. Return 1 at most, even if there are multiple Zhang San returns 1
        System.out.println(result.getMatchedCount());
    }

    /**
     * updateMulti
     */
    @Test
    public void updateMulti() {
        // Set query body and specific content of query criteria
        Criteria criteria = Criteria.where("name").is("Li Si");
        // Query set query criteria
        Query query = new Query(criteria);
        // Set which properties to modify
        Update update = new Update();
        update.set("age", 18);
        // People.class tells Spring Data MongoDB which class the above attribute is.
        // Class corresponds to the collection, and you know which property of the specific operation collection
        UpdateResult result = mongoTemplate.updateMulti(query, update, People.class);
        // Modify quantity. Returns the actual modified quantity in all matching results
        System.out.println(result.getModifiedCount());
        // Matching quantity
        System.out.println(result.getMatchedCount());
    }

    /**
     * remove
     * Delete by primary key
     */
    @Test
    public void remove() {
        //Delete by primary key
//        People peo = new People();
//        peo.setId("61e7b43790ea156906d8741e");
//        DeleteResult result = mongoTemplate.remove(peo);
//        System.out.println(result.getDeletedCount());
        //Delete according to entity class attribute name
/*        Query query = new Query(Criteria.where("name").is("Li Si ");
        //The second parameter tells spring data mongodb the attribute of the entity class corresponding to the name attribute
        DeleteResult remove = mongoTemplate.remove(query, People.class);
        System.out.println(remove.getDeletedCount());*/

        //Delete according to collection properties
        Query query = new Query(Criteria.where("name").is("Li Si"));
        //The second parameter tells spring data mongodb the collection attribute corresponding to the name attribute
        DeleteResult remove = mongoTemplate.remove(query, "people");
        System.out.println(remove.getDeletedCount());
    }


    /**
     * select
     * Query all
     */
    @Test
    public void select() {
        List<People> list = mongoTemplate.findAll(People.class);
        list.forEach(System.out::println);
    }

    /**
     * Query the first data
     */
    @Test
    void selectOne() {
        // Get the first data in the result
        // new Query() indicates that there are no conditions
        People people = mongoTemplate.findOne(new Query(), People.class);
        System.out.println(people);
    }

    /**
     * Condition query
     */
    @Test
    void find() {
        //Query select * from people where age > = 3 for age ≥ 13
        Query query = new Query(Criteria.where("age").gte(13));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Query by primary key
     */
    @Test
    void findById() {
        People peo = mongoTemplate.findById("61e7c20307207f50c83e8e71", People.class);
        System.out.println(peo);
    }

    /**
     * Query according to whether the field is empty
     */
    @Test
    void exists() {
        Query query = new Query(Criteria.where("name").exists(true));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Interval query
     * Query based on greater than or equal to and less than or equal to
     */
    @Test
    void range() {
        //select * from people where age <= 12 and age >= 14
        Query query = new Query(Criteria.where("age").gte(12).lte(14));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Regular expression query (fuzzy query)
     */
    @Test
    void regex() {
        // Regular in java does not need / / but mongodb does
        Query query = new Query(Criteria.where("name").regex("Zhang"));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }


    /**
     * Query de duplication results
     */
    @Test
    void findDistinct() {
        /**
         * findDistinct:
         * Query criteria query
         * Repeat according to which attribute. Is the property name of the POJO. The return value is the collection after de duplication of this property.
         * The entity class of the property.
         * Property as the generic type of the List collection in the result.
         */
        //select distinct name from people
        List<String> list = mongoTemplate.findDistinct(new Query(), "name", People.class, String.class);
        list.forEach(System.out::println);
    }

    /**
     * Multi condition query and
     */
    @Test
    void and() {
        Criteria c = new Criteria();
        //select * from people where name = "Li Si 123" and age = 12
        c.andOperator(Criteria.where("name").is("Li si123"), Criteria.where("age").is(12));
        Query query = new Query(c);
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Multi condition query or
     */
    @Test
    void or() {
        Criteria c = new Criteria();
        //select * from people where name = "Li Si" or age = 998
        c.orOperator(Criteria.where("name").is("Li Si"), Criteria.where("age").is(998));
        List<People> list = mongoTemplate.find(new Query(c), People.class);
        list.forEach(System.out::println);
    }


    /**
     * Conditional query, and and or
     */
    @Test
    void orAnd() {
        //select * from people where (name = "Zhang San" and age = 18) or (name = "Li Si" and age = 20)
        Criteria and1 = new Criteria();
        and1.andOperator(Criteria.where("name").is("Zhang San"), Criteria.where("age").is(18));
        Criteria and2 = new Criteria();
        and2.andOperator(Criteria.where("name").is("Li Si"), Criteria.where("age").is(20));
        Criteria c = new Criteria();
        c.orOperator(and1, and2);
        List<People> list = mongoTemplate.find(new Query(c), People.class);
        list.forEach(System.out::println);
    }

    /**
     * Result sorting
     */
    @Test
    void sort() {
        Query query = new Query(Criteria.where("age").gte(2));
        query.with(Sort.by(Sort.Direction.ASC, "age"));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Paging query
     */
    @Test
    void page() {
        Query query = new Query();
        /**
         * paging
         * page:Index, starting from 0, cannot be negative
         * size:Page size, must be greater than 0
         */
//        query.with(PageRequest.of(1,2));
        //Pagination after sorting
//        query.with(PageRequest.of(0, 2, Sort.Direction.DESC, "age"));
        //Sort before paging
        query.with(PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "age")));
        List<People> list = mongoTemplate.find(query, People.class);
        list.forEach(System.out::println);
    }

    /**
     * Aggregate operation: total number of query documents
     */
    @Test
    void aggregate01() {
        /**
         * Aggregation.group(String ...)Set grouping conditions. If there is no grouping, the parameters are omitted.
         * count() Take the total number
         * as() Alias the total number of queries
         */
        TypedAggregation<People> aggregation = TypedAggregation.newAggregation(People.class,
                Aggregation.group().count().as("count"));
        //Execute the aggregation command. The second parameter Map indicates that the returned results are put into the Map.
        AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Map.class);
        // Get the returned result.
        System.out.println(result.getUniqueMappedResult());
        System.out.println(result.getUniqueMappedResult().get("count"));
    }

    /**
     * Aggregation operation: calculate the total number of each group in groups
     */
    @Test
    void aggregate02() {
        /**
         * group()The parameter must exist in the People class.
         * Set the group parameter to indicate which attribute to group by
         */
        //select count(1) as count from people group by name
        TypedAggregation<People> aggregation = TypedAggregation.newAggregation(People.class,
                Aggregation.group("name").count().as("count"));
        AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Map.class);
        // Use this method when executing an aggregate function that returns multiple rows.
        List<Map> list = result.getMappedResults();
        list.forEach(System.out::println);
    }

    /**
     * Aggregation operation: Grouping calculation with query criteria
     */
    @Test
    void aggregate() {
        //Aggregation.match is written in front of group, which means that the filter condition is in the group first. If it is written later, it means grouping first in the filter condition
        //select count(1) as count from people where name = "Li Si" group by name
//        TypedAggregation<People> aggregation = TypedAggregation.newAggregation(People.class,
//                Aggregation.match(Criteria.where("name").is("Li Si"),
//                Aggregation.group("name").count().as("count"));

        //select count(1) as count from people group by name having name = "Li Si"
        TypedAggregation<People> aggregation = TypedAggregation.newAggregation(People.class,
                Aggregation.group("name").count().as("count"),
                Aggregation.match(Criteria.where("_id").is("Li Si")));
        AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Map.class);
        List<Map> list = result.getMappedResults();
        list.forEach(System.out::println);
    }
}

Topics: Java Database MongoDB