MongoDB documentation - basic use - using MongoDB basic statements in the client (dos window) / visualization tool

Adam:

        This article will describe and study the basic application of mongodb on the client side and the integration of mongodb in spring-boot to complete basic data addition, deletion, modification and query.

 Portal:

MongoDB Documentation--Basic Concepts - A Single Cheng Blog - CSDN Blog

MongoDB documentation--basic installation-linux installation (mongodb environment construction)-docker installation (mounting data volumes)-and detailed version comparison_一单成博客-CSDN Blog

MongoDB documentation--basic installation-linux installation (mongodb environment construction)-docker installation (mounting data volumes)-and detailed version comparison_一单成博客-CSDN Blog

MongoDB Documentation-Advanced Use-MongoDB Index-createindex() and dropindex()-Using regular expressions in MongoDB to find_One Single Cheng Blog-CSDN Blog

MongoDB document-advanced use-spring-boot integration using MongoDB---MongoRepository to complete additions, deletions, modifications and queries_One Single Cheng's Blog-CSDN Blog

MongoDB document-advanced use-spring-boot integration using MongoDB---MongoTemplate to complete additions, deletions, modifications and queries_One Single Cheng's Blog-CSDN Blog

Put the official article first

MongoDB CRUD operation- MongoDB-CN-Manual

This article is divided into:

        Use MongoDB statements in client (dos window)/visualizer

       Integrate mongodb in spring-boot and complete data addition, deletion, modification and query

Operate using mongodb statements in windows and visualization tools

How MongoDB creates databases and collections | MongoDB Chinese Community

MongoDB CRUD operation- MongoDB-CN-Manual

 Create a new query to demonstrate the effect:

 How does mongodb create databases and collections

        The first step in database learning must be to create databases and collections. Databases are used to store all collections, and collections are used to store all documents. These documents will contain the relevant "FieldName" and "Field" values ​​at a time.

At the same time, one thing we need to know is that documents can also exist in documents. The analogy with the entity class in java is much easier to understand. Attributes in a class can also be other entity classes. 

Here is an example of a document: 

{
    “Employeeid”:1,
    “EmployeeName”:“Smith”
}
冒号前面是field names
后面就是 field values

Create a database using the Use command

        Use the use command to create a new database:

use ExampleDB

The ExampleDB in this code is the newly created database file.

This mongodb use code can be compared to mysql :

IF NOT EXISTS 
    (SELECT * FROM sys.databases WHERE name = 'ExampleDB') 
        CREATE DATABASE ExampleDB;

The sql of this example is an effect when executed in mysql. 

Code explanation:

        1. Use the use command to create a database in mongodb. If the database does not exist, a new database will be created.

        2. Also use the database if it exists.

You can see that the execution was successful. After the use statement is successfully executed, mongodb will automatically switch to the created database.

Use insert() to create a collection/table

The simplest way to create a collection is to insert a record (nothing but a document with field names and values) into the collection. If the collection does not exist, a new collection will be created.

use ExampleDB

db.ExampleDB.insert
(
	{
		"员工编号":1,
		"员工姓名":"阿丹"
	}
	
)

 Explain the syntax:

        db: is an object representing a connection to a database. Before using this language, a database connection needs to be established. to access the database in code.

       ExampleDB: The name of the collection to operate on. If there is no such collection, this collection will be created.

  {
        "员工编号":1,
        "员工姓名":"阿丹"
    }

above is a document

        "Employee number": is a field names

        "The value of the employee number": it is value

 Notice:

        If there is no data in this library in mongodb, using such an insert statement will create a new library like this

        It is not perfect when using the above statement to insert. Because this will cause our new document to be added to a collection with the same name as the library. Be careful.

 insert array in mongodb using insert()

Try to pass in multiple documents multiple times at once in the form of an array.

Completion steps thought:

        1. Create a javascript variable named Example array to hold the document array

        2. Add the value with the field name and the required document to the variable

        3. Use the insert command to insert an array of documents into the collection

#定义数组
var Example = [
	{
		"员工编号":2,
		"员工姓名":"帅丹"
	},
	{
		"员工编号":3,
		"员工姓名":"大力丹"
	},
	{
		"员工编号":4,
		"员工姓名":"快乐丹"
	}
]
#将定义的数据添加到ExampleDB集合中
db.ExampleDB.insert(Example)

This is how batch addition is done in MongoDB.
 Now you can see that three pieces of data have been successfully added. That is three documents.

 Use the query statement and specify to print in JSON format

        The most commonly used format in the previously used document format is the form of json. It is even more because if we get a string in the form of json. We can easily convert this json string into our entity class.

        The full name of the json format is the JavaScript Ojbect Notation format (very friendly to those of us who type java). It is a format that stores information regularly and is easy to read.

        Then let's use the statement to complete the example of printing json:

db.查询使用的集合.find().forEach(printjson)

Execute and try:

 

 Code method and parameter explanation:

  • db.ExampleDB.find(): This statement uses find()the method to query all documents in the ExampleDB database. find()The method returns a cursor object that contains all documents that meet the query criteria.
  • forEach: This method is used to traverse each document in the cursor and perform the specified operation on each document.
  • printjson: This function is used to print the document to the console in JSON format

Among them, find() will find all by default if nothing is written in the brackets.

How to set the primary key ID?

By parsing the return value given to us by MongoDB just now, we can see that the employee number is used as the primary key id in the business logic. But found that mongodb itself generated an irregular string field. "_id". Now we need to set this "_id" as our primary key id.

In MongoDB, the _id field is the primary key of a collection so that each document can be uniquely identified within the collection. The _id field contains a unique ObjectID value.

By default, when inserting a document in a collection, if you don't add a field name with _id in the field name, MongoDB will automatically add an Object id field

So the principle is that as long as we have this field named "_id" when we add it, we can complete the replacement of the primary key. The id generated by the system is no longer used.

Let's try it out:

Use the code:

db.ExampleDB.insert
(
	{
		"_id":1,
		"员工姓名":"代码阿丹"
	}
	
)

 I specified the field name in this document: "_id"

 It shows that the addition is successful. Use the query output in the previous section to check whether the id of the code Adan is 1. Replace the id generated by the system itself.

It can be seen that the rule replacement of the primary key id is completed.

 Explain that we can use the assignment to the field name "_id" as the primary key of the collection.

Use the query statement find() in mongodb to query mongodb documents

        Through the execution of conditional query statements, we can get more accurate data from mongodb. and combination data. The more accurate the data obtained from the background, the less effort will be required for subsequent development.

        Then MongoDB provides a function called db.collection.find(), which is used to retrieve documents from the MongoDB database.

Basic query operations:

        Basic query operations include simple operations such as fetching all documents in a MongoDB collection.

        Because we created a new ExampleDB collection in our previous operation. So we can execute the following command.

db.ExampleDB.find({})

Instruction analysis:

        db.ExampleDB.find({}) What this MongoDB statement does is find all documents in the ExampleDB database.

find() The method is the method used to query documents in MongoDB, it accepts a query condition as a parameter, and returns all documents that meet the condition. In this example, the query condition is an empty object  {}, indicating that there are no constraints, so all documents in the database will be returned.

{} This symbol represents an empty query condition, and other conditions can also be used to limit the results of the query. For example, you could use  { "员工姓名": "阿丹" } something like this to query for documents where the employee name is "Adan", or something like this  { "员工编号": { $gt: 100 } } for documents where the employee number is greater than 100.

Therefore, db.ExampleDB.find({}) the function of this statement is to return all documents in the ExampleDB database, and  {} it means that there are no restrictions, and all documents will be returned.

conditional query

Clear conditional query

        For example, I want to query the employee whose employee number is 1. Below is an example:

#查询员工编号为1的员工
db.ExampleDB.find({"员工编号":1}).forEach(printjson)

This statement uses {} and square brackets, and uses the form of json in the square brackets to specify the rules to query the specified employee number.

range query

        With a greater than search condition, it actually searches for those documents that are greater than the specified value.

        For example, I want to query documents with employee numbers greater than 2. The following is an example:

#查询员工编号大于2的员工
db.ExampleDB.find({"员工编号":{$gt : 2}}).forEach(printjson)

 explain:

        $gt selects the operator for the query, meaning to use the greater-than sign expression.

 Provide you with the relevant judgment expressions;

  • $lt: less than
  • $eq:equal
  • $ne:not equal to
  • $gt:greater or equal to
  • $lt: less than or equal to

MongoDB Cursor Tutorial: Learn by Example

        When searching for documents in a collection using the db.collection.find() function, the result returns a pointer to the collection of documents, known as a cursor. Similar to pointers.

        By default, cursors will automatically iterate as query results are returned. Of course it is possible to explicitly display the result directories returned in the cursor one by one.

        For example, if there are three documents in the collection, the cursor is initialized to point to the first document, and then all documents in the collection are traversed.

 Sample code:

#演示游标
var myExampleDB = db.ExampleDB.find({});
while(myExampleDB.hasNext()){
	print(tojson(myExampleDB.next()))
}

 Code explanation:

        What this code does is find all documents in the ExampleDB database and print each document to the console in JSON format.

        First,  db.ExampleDB.find({}) all documents in the ExampleDB database are queried through the method, and a cursor object is returned  myExampleDB.

        Then, use  while a loop to traverse each document in the cursor until the documents in the cursor have been traversed. In the body of the loop, use  tojson() a function to convert each document to JSON format and  print() a function to print the JSON to the console.

Overall, what this code does is query all documents in the ExampleDB database and print each document to the console in JSON format

MongoDB limit query result

        This modifier is used to limit the number of documents returned in the query result set. Below is an example.

#limit结果
db.ExampleDB.find().limit(2).forEach(printjson)

The syntax and usage are similar but not the same as in mysql. The number of parameters in this function will find out a few documents.

Sorting in MongoDB

In MongoDB, it is supported to formulate the order of the documents to be returned according to the ascending or descending order of any key in the collection.

Sample code:

#根据员工编号倒序排序
db.ExampleDB.find().sort({ 员工编号: -1}).forEach(printjson)

Here it clearly shows the documents returned in descending order by Employeeid.

A value of 1 is in ascending order.

Counting function Count() in MongoDB

The concept of aggregation is to perform calculations on the results returned in a query. For example, suppose we want to know how many documents are in the collection based on the triggered query, then MongoDB provides the count() function.

Allows us to query the number of documents.

Let's look at an example.

#查看集合中文档数量
db.ExampleDB.count()

Here is some usage of count() function

In MongoDB, count() functions are used to count the number of documents in a collection that meet specified criteria. count() The function takes a query condition as an argument and returns the number of documents that meet the condition.

Here are some  count() examples of using functions:

Count the number of all documents in a collection:

db.myCollection.count({})

Count the number of documents in a collection for a specified condition:

db.myCollection.count({ "key": "value" })

Use  match the pipeline operator to count the number of documents in a collection that match a condition:

db.myCollection.aggregate([
  { $match: { "key": "value" } },
   { $count: "count" }
])

Use  match the and  group pipeline operator to count the number of documents after grouping:

db.myCollection.aggregate([
   { $match: { "key": "value" } },
   { $group: { _id: "groupKey", count: { $sum: 1 } } }
])

In the above example, count() the functions are used to count the number of all documents in the collection, count the number of documents that meet certain conditions, and use the  match and  group pipeline operators to count the number of grouped documents.

Delete file remove() in MongoDB

In MongoDB, the db.collection.remove() method is used to remove a document from a collection. All documents can be removed from a collection, or only those that meet certain criteria.

If only the remove command is issued, all documents will be removed from the collection.

The following code example demonstrates how to delete a specific document from a collection.

#删除员工标号为4的文档
db.ExampleDB.remove({员工编号:4})

You can see the syntax for deleting the corresponding field name and value.

 Update MongoDB documents using Update()

MongoDB provides the update() command to update the documents of a collection. To update only the documents to be updated, a condition can be added to the update statement so that the selected documents are updated.

The basic parameters in this command are the conditions under which the document needs to be updated, followed by the modification that needs to be performed.

Operation idea:

  1. issue an update command;
  2. Select the criteria to be used to determine which documents need to be updated. In our case, we want to update the document with employee ID 22;
  3. Use the set command to modify the field name;
  4. Select the field name to modify and enter the new value accordingly.
#修改员工标号为1的名字
db.ExampleDB.update(
	{"员工编号":1}, 
	{
		$set:{
			"员工姓名":"库库帅阿丹"
		}
	}
)

 It shows that a record meets the conditions, and a record modifies the relevant fields! ! !

Here are some update usages

This code is to use the function of MongoDB  update() to update the value of the "Employee Name" field in the document whose field value is 1 named "Employee Number" to "Kuku Shuai Adan".

Specifically, update() the function accepts two parameters:

  1. Query criteria specifying the documents to update. In this example, the query condition is  {"员工编号":1}to update the document whose "employee number" field value is 1.
  2. Update operation, specify the update operation to be performed on the document. In this example, the update operation  { $set: { "员工姓名": "库库帅阿丹" } }is to update the value of the "Employee Name" field to "Kuku Shuai Adan".

Among them, the update operation can use the following operators:

  • $set: Set the value of the specified field.
  • $unset: Delete the specified field.
  • $rename: Rename the specified field.
  • $inc: Increment the value of the specified field.

In addition to the above example, update() the function can also take other parameters to control the update behavior, such as  multi parameters (specifying whether to update multiple documents) and  upsert parameters (specifying whether to insert new documents).

In short, update() the function is a function used to update documents in MongoDB, which can easily modify the documents in the database.

Guess you like

Origin blog.csdn.net/weixin_72186894/article/details/132075991