MongoDB Basic Operations

[TOC]

1. Configure information

1.1 Automatic Restart Configure the MongoDB service

Use WIN + R to enter services. MSC and press Enter to find MongoDB Serever(MongpDB) service.

The default MongoDB port number is 27017

2. Core concepts

2.1 library < DataBase >

Libraries in MongoDB are similar to databases in Mysql, which are used to isolate different applications through different libraries.

Multiple libraries can be built, each with its own collection and permissions, and different databases are placed in different files;

The default database is test, and the database is stored in the specified data directory.

2.1.1 Viewing All Libraries
  • > show databases; | show dbs;

  • From the printed information there are three libraries;

    – admin 0.00 GB

    – the config 0.00 GB

    – local 0.00 GB

⚠ ️ note:

The admin, config, and local libraries are reserved MongoDB libraries. Do not delete it and do not operate on it;

Admin: From a permission perspective, this is the root library. If you add a user to the database, the user automatically inherits all database permissions. Some specific server-side commands can only be run from this database.

For example: list all databases or shut down the server;

Config: when MongoDB is used for sharding Settings. The config database is used internally to store sharding information.

Local: This data is never copied and can be used to store any collection limited to a single server locally;

2.1.2 Creating or Switching over a Database

use DataBaseName;

⚠ ️ note:

Create only if the library in use does not exist, if it does, switch to the target library;

Use stands for create and use. The library is not displayed when there is no data in it.

The default database is the test library.

2.1.3 Deleting a Database

db.dropDatabase();

Delete the currently selected library;

⚠ ️ note:

Although delete does delete the database, but when you do not switch to another library or exit the db query current library is still displayed in this library;

2.2 Collection < Collection >

A collection in MongoDB is a document group (storing many documents), similar to a table in a Mysql database.

Collections exist in the database, a library can create multiple collections;

Each set has no fixed structure. This means that different formats and types of data can be inserted into the collection, but usually the data inserted into the collection will have some relevance;

2.2.1 Viewing collections

show collections; | show tables;

2.2.2 Creating a Collection

db.createCollection("collectionName", [options]);

The first parameter is to fill in the name of the collection, and the second parameter is to fill in the Settings. If options is not specified, the default configuration is used.

Options partial parameters:

field type describe
capped Boolean (Optional) If true, a fixed collection is created. A fixed set is a set with a fixed size;

If the parameter reaches its maximum value, it automatically overwrites the earliest document.When this value is true, the size argument must be specified;
size The numerical (Optional) Specify a maximum value, the number of bytes, for a fixed set;

If capped is true, you must specify the parameters for this field;
max The numerical (Optional) Specify the maximum number of documents to contain in a fixed collection;

🌰

db.createCollection("collectionNmae", {max: 100, capped: true, size:1000})
Copy the code

When a document is inserted into a collection that does not already exist, the collection is also automatically created;

2.2.3 Deleting a Collection

db.collectionName.drop();

2.3 Document < Document >

A document is a set of key-value pairs.

MongoDB documents do not need to set the same field, and the same field does not need the same data type, which is very different from relational databases.

This is also a very prominent feature of MongoDB;

🌰

{
	"name": "urbaneH"."drink": "water"
}
Copy the code
2.3.1 Inserting documents
  • A single document

db.collectionName.insert({name: "UrbaneH", age: 18});

  • Multiple document
db.collectionName.insertMany( [<Document1>, <Document2>, ......] , { writeConcern:1.// Write policy. The default value is 1, which requires confirmation of write operations.
		ordered: true // Specifies whether to write sequentially. Default: true;})// For example, insert can also be used without insertMany;
db.collectionName.insert([
  {name: "xiaohua"."age": 17},
  {name: "xiaohu"."age": 18}])Copy the code
  • Script way
for (let i = 0; i <= 100; i++){
	db.collectionName.insert({
		"_id": i,
		"name": "hahah"."age": i + 1; })}Copy the code

⚠ ️ note:

In MongoDB, each document has an id as a unique identifier. The id is automatically generated by default. If manually specified, the manually specified value will be used as the id value.

2.3.2 Querying collection ownership

db.collectionName.find();

2.3.3 Deleting a Document
db.collectionName.remove(
	<query>, / / conditions;
	{					// Delete the configuration object;
		justOne: <boolean>, // Delete only one data;
    		writeConcern: <Document> // The level of the exception to be thrown if an accident is thrown;});Copy the code

If justOne is not selected or the parameter is false, all matched documents will be deleted.

If remove does not have a condition (but still has {} at the condition to indicate an empty condition), remove all;

2.3.4 Updating documents
db.collectionName.update(
	<query>,
	<update>,
	{
		upsert: <boolean>,
		mulit: <boolean>,
		wirteConcern: <Document>
	}
);
Copy the code

Query: The query condition is similar to the part after SQL update query where.

Update: Update objects and some update operators (e.g. $, $inc,……) SQL update query (set);

Upsert: Optional. This parameter means whether to insert objNew if no update records exist. The default value is false. The < boolaen > type

Mulit: Optional. This parameter indicates whether to update only the first data found. The default value is false, and if true, all queried data is updated. The < Boolean > type

WirteConcern: Optional, level of exception thrown;

🌰

> db.collectionName.update({"name": "UrbaneH"}, {"name": "11", "bir": new date()})
-- This update is to meet the conditions of all the updated documents, equivalent to delete and then update;
> db.collectionName.update({"name": "UrbaneH"}, {$set: {"name": "xiaohua"}})
-- Keep the original data update, but only update the first data that meets the conditions;
> db.collectionName.update({"name": "UrbaneH"}, {$ser: {"name": "xiaohua"}}, {mulit: true})
-- Keep the original data update, update all the data that meet the conditions;
> db.collectionName.update(
	{"name": "UrbaneH"},
	{$set: {"name": "xiaohua"}},
	{
		mulit: true,
		upset: true})-- Keep the original data update, update all the data that meets the conditions, insert data when there is no condition;
Copy the code
2.3.5 Querying Documents

db.collectionName.find(query, projection);

Query: Optional use the query operator to specify the query conditions.

Projection: Optionally specifies the key to return using the projection operator. Query returns all key values in the document. You only need to omit this parameter. The default is omitted.

⚠ ️ note:

The default query is unstructured. If you want to make the results more structured and readable, you need to add pretty() to the end.

🌰

db.collectionName.find(query, projection).pretty();

2.3.5.1 Comparison Syntax
operation format sample Similar statements in an RDBMS
Is equal to the {<key>:<value>} db.col.find({"by":"UrbaneH"}).pretty() where by = 'UrbaneH'
Less than {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
Less than or equal to {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
Is greater than {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
Greater than or equal to {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
Is not equal to {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes ! = 50
2.3.5.2 AND query

db.collectionName.find({key1:value1, key2: value2});

If the same field appears, the last occurrence will prevail;

Where key1 = value1 AND key2 = value2;

2.3.5.3 OR query
db.collectionName.find({
	$or: [
		{key1: value1}, {key2: value2}
	]
}).pretty()
Copy the code

Similar to WHERE key1 = value1 OR key2 = value2;

2.3.5.4 Querying AND AND OR Information

db.collectionName.find({"age": {$gt: 50}}, $or: [{"name": "UrbaneH"}, {"name": "MongoDb"}]).pretty();

This is similar to WHERE age > 50 AND (name = “UrbaneH” OR name = “MongoDB”);

2.3.5.5 🌟 Query information in the array

db.collectionName.find({shuzu: "baohanneirong"})

⬆️ means to query the array in shuzu for documents containing Baohanneirong

Just use the field containing the array as the key and the value to be included as the value;

db.collectionName.find({shuzu: {$size: 3}});

⬆️ : queries the data whose shuzu length is 3

2.3.5.6 Fuzzy Query

In MongoDB, fuzzy query is implemented by regular expression.

Start with a slash End with a slash. There is no need to enclose the string with double quotation marks, for example:

Db. CollectionName. Find (name: {/ U /});

⬆️ : queries documents whose name contains U

If it is for the content of the array fuzzy query can also use the above method, MongoDB’s re can directly match all elements in the array;

For example, shuzu in one document: [” eat, “” drink,” “sleep”]

Db. CollectionName. Find ({shuzu: {/ eat /}});

⬆️ can also be matched

2.3.5.7 sorting

db.collectionName.sort({key1: 1, key2: -1});

1 is in ascending order, -1 is in descending order

2.3.5.8 paging

db.collectionName.find().sort({query}).limit(rows).skip(start);

1 ️ sort first according to the conditions needed;

2 ️ limit refers to the number of data per page;

3 discount ️ skip refers to page number of current display;

2.3.5.9 total number of article

db.collectionName.count();

db.collectionName.find({query}).counu();

2.3.5.10 🧹 to heavy

Db. CollectionName. Distinct (" fields ");

The return value is the remaining value of the corresponding field (after deduplication);

2.3.5.11 The specified field is displayed

This is also the work of projection mentioned above;

db.collectionName.find({name: "UrbaneH"}, {age: 0});

⬆️ indicates that the data whose name value is UrbaneH is queried, but the age field is not returned.

⚠ ️ note:

0 and 1 cannot be used together. 0: does not return. 1: return.

If 0 is used, all but its fields are returned; if 1 is used, only its fields are returned

2.4 Relationship Summary

RDBMS (Relational database) MogoDB (Non-relational database)
The DataBase < DataBase > The DataBase < DataBase >
Table < Table > Collection < Collection >
Line the < Row >” The Document < Document >
Column < Colume > Field < Field >

3. $type

instructions

The $type operator retrieves the matching data type in the collection based on the BSON type and returns the result.

type digital note
Double 1
String 2
Object 3
Array 4
Binary data 5
Undefined 6 Has been abandoned.
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
Symbol 14
JavaScript (with scope) 15
32-bit integer 16
Timestamp 17
64-bit integer 18
Min key 255 Query with - 1.
Max key 127

use

> db.collectionName.insert({
    title: 'PHP tutorial', 
    description: PHP is a powerful server-side scripting language for creating dynamic, interactive sites. '.by: 'UrbaneH',
    url: 'http://www.xxx.com',
    tags: ['php'],
    likes: 200
})
> db.collectionName.insert({title: 'the Java tutorial', 
    description: Java is a high-level programming language introduced by Sun Microsystems in May 1995. '.by: 'UrabaneH',
    url: 'http://www.xxx.com',
    tags: ['java'],
    likes: 150
})
> db.collectionName.insert({title: 'directing a tutorial, 
    description: 'MongoDB is a Nosql database '.by: 'UrabaneH',
    url: 'http://www.xxx.com',
    tags: ['mongodb'],
    likes: 100
})
Copy the code

🔧 Usage:

db.collectionName.find({"title" : {$type : 2}})
或
db.collectionName.find({"title" : {$type : 'string'}})
Copy the code

🖨 ️ output:

{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP tutorial"."description" : PHP is a powerful server-side scripting language for creating dynamic, interactive sites.."by" : "UrbaneH"."url" : "http://www.xxx.com"."tags" : [ "php"]."likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "The Java tutorial"."description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995.."by" : "UrbaneH"."url" : "http://www.xxx.com"."tags" : [ "java"]."likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "Directing a tutorial"."description" : "MongoDB is a Nosql database"."by" : "UrbaneH"."url" : "http://www.xxx.com"."tags" : [ "mongodb"]."likes" : 100 }
Copy the code

$type = ‘title’; $type = ‘title’; $type = ‘title’;

4. The Index < Index >

Indexes can often greatly improve query efficiency.

Without indexes, MongoDB must scan every file in the collection when reading data and select those records that match the query criteria.

The query efficiency of scanning the whole collection is very low, especially when dealing with a large amount of data, the query can take tens of seconds or even a few minutes, which is very fatal to the performance of the website.

An index is a special data structure. It is stored in a data set that is easy to traverse and read. An index is a kind of structure that sorts the values of one or more columns in a database table.

Indexes in MongoDB are fundamentally similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexing of any field or sub-field of a document in the MongoDB collection.

4.1 Creating An Index

db.collection.createIndex(keys, options)

The Key value is the index field that you want to create. 1 is used to create the index in ascending order. -1 is used to create the index in descending order.

You can also set the createIndex method to create an index with multiple fields (called a compound index in relational databases);

> db.colltectionName.createIndex({"title":1})
-- Create an index for the title field in ascending order;
> db.colltectionName.createIndex({"title":1, "description":- 1})
-- Create compound index title and description in ascending and descending order respectively;
> db.colltectionName.createIndex({open: 1.close: 1}, {background: true})
-- Specifies parameters for creating an index
Copy the code

The options of the attribute:

Parameter Type Description
background Boolean The index creation process blocks other database operations. Background specifies how to create an index in the background. “Background” defaults tofalse.
unique Boolean Whether the created index is unique. Specifies true to create a unique index. The default value isfalse.
name string The name of the index. If not specified, MongoDB generates an index name from the join index’s field name and sort order.
dropDups Boolean ** Version 3.0+ is deprecated. ** Whether to delete duplicate records when creating unique indexes, specify true to create unique indexes. The default value isfalse.
sparse Boolean Disable indexing for field data that does not exist in the document; This parameter is important because if set to true, documents that do not contain the corresponding field will not be queried in the index field. The default value isfalse.
expireAfterSeconds integer Specify a value in seconds to complete the TTL setting and set the lifetime of the collection.
v index version The version number of the index. The default index version depends on the version mongod was running when the index was created.
weights document Index weight value. The value between 1 and 99,999 represents the score weight of this index relative to other index fields.
default_language string For text indexing, this parameter determines the list of stop terms and rules for stems and lexical devices. Default: English
language_override string For text indexes, this parameter specifies the name of the field to be included in the document, overriding the default language, which is language.

4.2 Index base API

> db.colltectionName.getIndexes()
-- View the collection index
> db.colltectionName.totalIndexSize()
-- View the set index size
> db.colltectionName.dropIndexes()
-- Delete all indexes of the set
>Db. ColltectionName. DropIndex (" index name)"-- Deletes the specified index
Copy the code

4.3 Composite Index

A composite index is primarily an index maintained by two fields;

db.colltectionName.createIndex(
	{
  	name: 1,
  	age: - 1
  },
  {
  	name: "name_age_index"
  }
);
Copy the code

⚠ ️ note:

Both the composite index and the traditional relational database in MongoDB are consistent with the left prefix principle.

5. <Aggregate>

In MongoDB, aggregate is mainly used to process data (such as statistical average, sum, etc.) and return calculated data results.

This is similar to count(*) in an SQL statement.

5.1 the operator

expression describe The instance
$sum Calculate the sum. db.colltectionName.aggregate([{group : {_id : “by_user”, num_tutorial : {
s u m : sum : ”
likes”}}}])
$avg Calculate the average db.colltectionName.aggregate([{group : {_id : “by_user”, num_tutorial : {
a v g : avg : ”
likes”}}}])
$min Gets the minimum value corresponding to all documents in the collection. db.colltectionName.aggregate([{group : {_id : “by_user”, num_tutorial : {
m i n : min : ”
likes”}}}])
$max Gets the maximum value corresponding to all documents in the collection. db.colltectionName.aggregate([{group : {_id : “by_user”, num_tutorial : {
m a x : max : ”
likes”}}}])
$push Adding a value to an array does not determine whether there are duplicate values. db.colltectionName.aggregate([{group : {_id : “by_user”, url : {
p u s h : push: ”
url”}}}])
$addToSet Adding a value to an array determines whether there are duplicate values. If the same value already exists in the array, it is not added. db.colltectionName.aggregate([{group : {_id : “by_user”, url : {
a d d T o S e t : addToSet : ”
url”}}}])
$first Get the first document data according to the ordering of the resource documents. db.colltectionName.aggregate([{group : {_id : “by_user”, first_url : {
f i r s t : first : ”
url”}}}])
$last Gets the last document data according to the ordering of the resource documents db.colltectionNameaggregate([{group : {_id : “by_user”, last_url : {
l a s t : last : ”
url”}}}])

5.2 Operation Example

5.2.1 Calculate the total number of articles written by each author

⬇️ Data within the collection

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb'.'database'.'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb'.'database'.'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j'.'database'.'NoSQL'],
   likes: 750
},
Copy the code
> db.colltectionName.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "runoob.com",
         "num_tutorial" : 2
      },
      {
         "_id" : "Neo4j",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}
Copy the code

1 one ️ Group the data in the set

$group is used for grouping, and the parameter __id is used to declare which field of the original data is used as the grouping index. ⬆️🌰 is the group aggregation operation of the field by_user, and this field is used as the index of the new collection;

2 discount ️ Selective polymerization function

The num_tutorial parameter is simply understood as a way to aggregate grouped data. ⬆️🌰 select $sum to sum, because there is no information about the number of articles written by the author in the original data, and each piece of data is the data of an article, so $sum: 1 is used here to mean that each piece of data adds 1. If you choose to accumulate the value of the original data, the same method is the $field name;

5.2.2 Use of $push
> db.colltectionName.aggregate([{$group : {_id : "$by_user", urls : {$push: "$url"}}}])
--- 
{
	"_id": xxxx,
	"urls": ["www.baidu.com"]
},
{
	"_id": xxxx1,
	"urls": [
   	"www.4399.com",
    "www.7k7k.com",
    "www.4399.com"
  ]
}
Copy the code

It adds all the urls of the grouped authors into an array and uses urls as field names.

If you don’t want duplicate data, you can use $addToSet

6. SpringBoot integrates MongoDB applications

6.1 Environment Construction

1 One ️ introduce MomgoDB’s dependency MongoTemplate in POM file

<dependency>
 <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Copy the code

2 discount ️ Write MongoDB configuration in application.properties file

⬇️ can be used when MongoDB does not have security protocol enabled
spring.application.name=spring-boot-mongodb
spring.data.mongodb.uri=mongodb://localhost/test
# mongodb://(host) (port)/(database);
If no port is specified, default 27017;
⬇️ is used if the password is used
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.username=username
spring.data.mongodb.password=password
Copy the code

Spring Data (which will automatically inject MongoTemplate) actually handles MongoDB;

6.2 Application of collections

mongoTemplate.createCollection("production");

⬆️ create a collection called Production;

⚠ ️ note:

If the Collection already exists, an error will be reported indicating that Collection already exists. NS: test.production

If you can’t determine the existence of the collection and use mongoTemplate. CollectionExists to determine whether there is this collection, method returns a Boolean value, if there is a return true, there is no return flase;

🌰

// Create a collection
    @Test
    public void Times(a) {
        if(! mongoTemplate.collectionExists("production")) {
            mongoTemplate.createCollection("production");
        } else {
            System.out.println("Set already exists;"); }}Copy the code

mongoTemplate.dropCollection("production");

⬆️ deletes a collection called production;

❕ tip:

In MongoDB, deleting a statement is different from creating one. The statement can be deleted multiple times without checking whether it exists. (You can delete it if it doesn’t exist!)

6.2.1 Relevant notes
  • @Document
    • 2. To apply to a class;
    • What it does: Maps an object of this class as a piece of data in MongoDB;
    • Properties:value.collection) to specify the collection name of the operation;
  • @ID
    • Modifier scope: applied to member variables and methods;
    • Is used to map the value of a member variable to_idThe value of the;
  • @Field
    • Modifier scope: applied to member variables and methods;
    • Use to map member variables and values to a key-value pair in a document.
    • Properties:name.value) to specify the name of the key in the document,The default is the member variable name;
  • @Transient
    • Modifier scope: applied to member variables and methods;
    • Function: Used to specify the change member variable, does not participate in the document serialization;

6.3 Application of Documents

6.3.1 Adding documents
    // Add the document
    @Test
    public void addDocument(a) {
        User user = new User(888."UrbaneH".88888.new Date());
// mongoTemplate.save(user); // the existing _id overwrites the old data.
        mongoTemplate.insert(user); // if the _id exists, the primary key is duplicated.
    }
Copy the code

Save and insert are both save operations and can be saved, but not exactly the same.

⚠ ️ note:

DuplicateKeyException: DuplicateKeyException indicates primary key duplication. While save will cover the repeated data;

Batch processing operations: Insert can be used to insert the entire data at once, which is very efficient. Save requires traversing the entire data and one-time insertion or update, which is inefficient (you can only use the for loop to insert the data one by one).

	List<User> users = Arrays.asList(
		new User(1."hahaha".7768.new Date()),
		new User(2."What's for today?".77777.new Date()),
		new User(3."Very hungry".12345.new Date())
	);
  mongoTemplate.insert(users, User.class);
Copy the code

The first parameter is the object to be inserted, and the second parameter is the name of the collection. User.class is written because @document (“production”) declares the collection in this file.

6.3.2 Document Query
6.3.2.1 Querying All Information
// Query the document
@Test
public void queryDocument(a) {
		List<User> all = mongoTemplate.findAll(User.class);
		List<User> all = mongoTemplate.findAll(User.class, "production");
		all.forEach(System.out::println);
	}
Copy the code

There are two arguments in findAll. The first argument is mandatory and is the object of the returned class, and the second argument is optional and is the name of the collection to retrieve the data from. It’s actually defined in the class;

6.3.2.2 Querying Information Based on ID

⬇️ The query ID is 888.

User byId = mongoTemplate.findById(888, User.class);
System.out.println(byId);
Copy the code
6.3.2.3 Condition Query
List<User> users = mongoTemplate.find(new Query(), User.class);
users.forEach(System.out::println);
Copy the code

If an empty Query object is passed in, all data in the set is returned.

6.3.2.3 Equivalent Query
	@Test
	public void queryDocument(a) {
		Query query = Query.query(Criteria.where("name").is("UrbaneH"));
		List<User> users = mongoTemplate.find(query, User.class);
		users.forEach(System.out::println);
	}
Copy the code

The usage is the same as described in 2.3.5.1 Comparison syntax.

Another smart part of this section is that if you have previously changed the name of a member object using @field, it will be automatically converted according to the annotation without special modification.

For example:

If you change the alias of name to username, then either name or username is valid within where, with the same result.

6.3.2.4 Unequal query

With reference to2.3.5.1 Comparison SyntaxAnd equivalent enquiries above

6.3.2.5 AND query

⬇️ The value of query name is UrbaneH and the ID is 888.

		@Test
    public void queryDocument(a) {
        Query query = Query.query(Criteria.where("name").is("UrbaneH").and("_id").is(888));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);

    }
Copy the code

Simply add and after where;

⚠ ️ note:

Be sure to pay attention to the field type;

6.3.2.6 OR query

⬇️ query name for hungry or what to eat today;

		@Test
    public void queryDocument(a) {
        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("name").is("Very hungry"),
                Criteria.where("name").is("What's for today?")); Query query = Query.query(criteria); List<User> users = mongoTemplate.find(query, User.class); users.forEach(System.out::println); } --- --- --- User(id=2, name= What do you eat today, salary=77777.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=3, name= hungry, salary=12345.0, birthday=Sun Mar 06 18:05:12 CST 2022)
Copy the code

⚠ ️ note:

Using OR differs from using AND in the same way

1 one Criteria object needs to be instantiated first;

2 discount ️ directly connected with an orOperator method;

3 multiple Criteria are added in orOperator, each of which belongs to a condition (AND can also be directly added after WHERE of each condition for AND operation);

6.3.2.7 sorting

⬇️ is arranged in ascending order according to salary;

// Query the document
    @Test
    public void queryDocument(a) {
        Query query = new Query().with(Sort.by(Sort.Order.asc("salary")));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }
--- 
---
---
User(id=1, name=hahaha, salary=7768.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=3, name= hungry, salary=12345.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=2, name= What do you eat today, salary=77777.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=888, name=UrbaneH, salary=88888.0, birthday=Sun Mar 06 17:38:33 CST 2022)
User(id=8888, name=UrbaneH, salary=88888.0, birthday=Sun Mar 06 17:41:51 CST 2022)
Copy the code

1 one ️ Create a Query object;

2 discount ️ using with connection, call sort.by;

3 call sort.order. asc(” field name “) in sort.by;

⚠ ️ note:

Asc: indicates ascending order.

Desc: indicates descending order.

6.3.2.8 paging

⬇️ each page is divided into three, query the first page (starting from 0, the first page is 0);

@Test
    public void queryDocument(a) {
        Query query = new Query().with(Sort.by(Sort.Order.asc("salary")));
        query.limit(3).skip(0);
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }
---
---
---
User(id=1, name=hahaha, salary=7768.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=3, name= hungry, salary=12345.0, birthday=Sun Mar 06 18:05:12 CST 2022)
User(id=2, name= What do you eat today, salary=77777.0, birthday=Sun Mar 06 18:05:12 CST 2022)
Copy the code

Just use limit and skip on top of the previous sorting;

Limit: indicates the number of data items per page.

Skip: indicates the current page;

6.3.2.9 Querying the Total Number of Entries

⬇️ Query the total number of entries. If conditions exist, add conditions in Query.

System.out.println(mongoTemplate.count(new Query(), User.class));
Copy the code
6.3.2.10 to heavy

⬇️ remove the repeated data of the specified condition, if the condition is empty, remove all;

mongoTemplate.findDistinct(new Query(), "name", User.class, String.class);
Copy the code

✒️ You can set four parameters:

The first parameter specifies the conditions for the data to be de-duplicated. If it is null, it specifies all data.

The second parameter is the field name, which field needs to be de-weighted;

The third parameter is the object of the document;

The fourth argument is the data type of the erased field, such as String (String.class) and Integer (integer.class).

6.3.2.11 🌟 Use the native script

MongoTemplate also provides built-in methods for more native authoring;

⬇️ is to query the data whose name is UrbaneH.

		@Test
    public void queryDocument(a) {
        Query query = new BasicQuery("{name: 'UrbaneH'}");
        mongoTemplate.find(query, User.class).forEach(System.out::println);
    }
Copy the code

Simply use BasicQuery, a subclass of Query, to write native commands into it;

If you need to return the specified field, you can directly write the corresponding original command in a parameter.

🌰

new BasicQuery("{name: 'UrbaneH'}"."{name: 1}");
Copy the code
6.3.3 Document Updates
6.3.3.1 Updating The first data

⬇️ updates user UrbaneH’s salary to 1 followed by many zeros and birthday to the present time;

    @Test
    public void updateDemo(a) {
        // Update first;
        Update update = new Update();
        update.set("salary".10000000000L)
                .set("birthday".new Date());
        System.out.println(mongoTemplate.updateFirst(new Query(
                Criteria.where("name").is("UrbaneH")
        ), update, User.class));
    }
Copy the code

Use 1 ⃣ ️ mongoTemplate. UpdateFirst;

2 discount ️ Determining the conditions of data to be updated;

3 one data Update object selection, need to use set to pass in a key-value pair for data modification, can connect multiple sets;

4 discontinuous object;

6.3.3.2 Updating Multiple Pieces of Data

Use the same method as above, but instead of calling the methodmongoTemplate.updateMulti;

6.3.3.3 Inserting updates

⬇️ update name to my full salary, insert data if not present;

    @Test
    public void updateDemo(a) {
        mongoTemplate.upsert(
                new Query(
                        Criteria.where("name").is("I'm full.")),new Update()
                        .set("salary".7758521),
                User.class
        );
    }
Copy the code

If the data to be updated cannot be queried, insert this data.

⚠ ️ note:

The inserted data will only have query conditions and update conditions. For example, the above 🌰 will only insert data with default ID, name and salary.

However, if read by SpringBoot, the specified object will still be generated, but no data value is null.

If you want to specify an ID, use.setonInsert (“_id”, specific ID);

6.3.4 Deleting documents
    @Test
    public void updateDemo(a) {
        mongoTemplate.remove(new Query(
                Criteria.where("name").is("I'm full.")
        ), User.class).sout;
    }
Copy the code

Usage is basically the same as query

If the query condition is empty, all data is deleted.

If there is a condition, delete the data of the specified condition.

The resources

1. [B station programming bad people] : www.bilibili.com/video/BV1vL…

2. [novice tutorial] : www.runoob.com/mongodb/mon…

3. [] mongo official document: docs.mongodb.com/manual/intr…