MongoDB experiment - MongoDB shell operation

MongoDB shell operations

Experimental principle

MongoDB shell is an executable file, an interactive JavaScript shell that comes with MongoDB, and is located in the /bin folder under the MongoDB installation path. To start the MongoDB shell, execute the command mongo. This will launch the shell in a console prompt. MongoDB shell provides multiple commands. Below are listed several MongoDB shell commands and their uses.

image-20221014215526918

1. MongoDB shell script programming

1. Use command line programming –eval to execute JavaScript expressions

​ Parameter –eval accepts a JavaScript string or JavaScript file. The following command starts the MongoDB shell, connects to the database test, executes db.getCollectionNames() on the database, and outputs the result as a JSON string.

step:

1) Create a new collection student in the test database and add documents. The command is as follows:

MongoDB shell side operation

>use test

>db.student.insert({sno:”001”,sname:”zhangsan”})

>exit

2) Enter in the console:

> mongo test --eval “printjson(db.getCollectionNames())”

image-20221014225002936

2. Use the load() method in the MongoDB shell to execute the script

1) Create the shell_script.js file. The path of the file is D:\Junior Experiment\nosql\NoSQL guide book\test1document\shell_script.js. The file code is as follows:

print("Hostname:");

print("\t"+hostname());

print("Date:");

print("\t"+Date());

db = connect("localhost/admin");

print("Admin Collections:");

printjson(db.getCollectionNames());

2) Execute the command mongo file address + shell_script.js. The command execution result is as shown in the figure.

image-20221015091614832

3. Specify the JavaScript file to be executed in the command mongo

​ MongoDB shell loads and executes the script file generate_words.js. Assume the path to the file is

D:\JuniorExperiment\nosql\NoSQLguidebook\test1document\generate_words.js。

1) Enter load("D:\JuniorExperiment\nosql\NoSQLguidebook\test1document\generate_words.js") on the MongoDB shell (so the address is too long, so I changed the file path)

image-20221015093917124

2) Enter the command show dbs, and you can see that the custom database words is generated.

3) Enter the command use words to switch to the words database.

4) Enter the command show collections to view the collection names contained in the words database. The command execution result is shown in the figure.

image-20221015094104309

5) Enter the command db.word_stats.find().pretty() to view all documents in the word_stats collection. The command execution result is shown in the figure.

image-20221015094351269

2. MongoDB shell operation

Experiment content

Practice creating collections, deleting collections, inserting data, updating data, deleting data, querying data, etc. in MongoDB.

Experimental steps

1. Start the MongoDB shell.

image-20221014220036475

2. Switch to the admin database and use the root account

image-20221014220420094

When authorizing the admin account, the connection failed Error: Authentication failed.. Causing robomongo to be unable to connect

The solution is to manually add the admin account. After the creation is successful, db.auth('root','strongs') again returns 1

image-20221015101018782

3. Check the current database status

image-20221015101129224

4. Display the current MongoDB version

image-20221015101221215

5. Query the names of all local databases

image-20221015101438210

6. Switch to the mydb database. If the database does not exist, it will be created after inserting the first piece of data.

image-20221015102105065

7. Create a collection (a collection is equivalent to a table in a relational database)

image-20221015102213620

8. Query all collections under the current library

image-20221015102255718

9. Query all collections under the current library (collections)

image-20221015102336376

10. Insert data into the collection mycollection. (If the collection does not exist, MongDB will automatically create the collection when inserting data)

image-20221015103133623

11. Use the insert method to add data. If you add a document, you can also declare the object first and then add it. For example:

image-20221015104901354

image-20221015104941859

12.MongoDB will automatically generate an "_id" value for each inserted object. You can also specify this value yourself when inserting, for example:

image-20221015105338678

13. Query the data in the collection mycollection

image-20221015105437434

MongoDB provides two update operations: update() and save()

①The update() update operation requires at least two parameters, and its syntax is: db.collection.update(criteria, objNew, upsert, multi)

criteria: update query conditions, similar to the value after where in the sql update query.

objNew: update object and some update operators (such as , ,, inc...), etc., can also be understood as the value after set in the sql update query.

upsert: If there is no update record, whether to insert objNew, true means insert, the default is false, not insert.

multi: MongoDB defaults to false, and only updates the first record found. If this parameter is true, all multiple records found based on conditions will be updated.

14. Modify the salary based on the username, and increase the salary to 600 for data with username 'zhangyu'

image-20221015114835280

15. Increase the age field value of the data with username 'wangkaiyue' by 1

image-20221015124059839

②The syntax of save() is: db.collection.save(x), x is the object to be updated, which can only be a single record. You can also use Save to perform the insertion operation. If there is no identical "_id" in the system, the insertion operation will be performed. If there is, the original value will be overwritten and the update operation will be performed.

16. Update the data with _id 10000001.

image-20221015125728327

17. Query the mycollection collection again to verify the above update operation

image-20221015125819692

18. Delete the data with username 'yuhaowen'.

image-20221015130006073

19. Delete all data in the collection mycollection

image-20221015130048687

The delete syntax is as follows:

db.mycollection.remove(
			<query>,
			{
				justOne:<boolean>,
				writeConcern:<document>
			}
		)

Parameter Description:

query: (optional) Conditions for deleted documents.

justOne : (optional) If set to true or 1, only one document will be deleted. Default false

writeConcern: (optional) The level at which the exception is thrown.

20. Rename the collection from mycollection to mcollection

image-20221015130404807

21. Delete the collection mcollection

image-20221015130436672

22. Delete the current database

image-20221015130511350

This experimental shell operation ends!

3. MongDB query

Experiment content

1. Use find or findOne function and query documents

2.MongoDB conditional query

3.MongoDB AND and OR queries

4.MongoDB $type operator

5.MongoDB regular expressions

Experimental steps

1. Start the MongoDB shell

image-20221015131312431

2. Switch to the admin database and use the root account

image-20221015131412422

3. Insert experimental data

image-20221015132243437

4. Count the number of data items in the collection

image-20221015132318293

5. Find is used in MongoDB to perform queries. The query returns a subset of a set, and the subset ranges from 0 to the entire set.

combine. The first parameter of find determines which subsets are to be returned, and its form is also a set.

An empty document query will match the entire content of the collection. If the query document is not specified, the default is {}.

6. Query the first piece of data

image-20221015132655681

Note that the O in findOne must be capitalized

7. Query all data after Article 1

image-20221015132825319

8. Skip the second item and query the last two data

image-20221015132938356

This command can be used for paging, Limit is pageSize, Skip is page *pageSize

9. Limit query to 3 pieces of data

image-20221015133127181

10. Query the number of records in the result set. (Query the number of salaries less than 300 or greater than 400)

image-20221015133414286

Query the data of the specified column. You can specify the desired key through the second parameter of find (or findOne), which will save

It saves the amount of data transmitted and saves the client’s time and memory consumption in decoding documents.

11. Query the 'age' column and 'salary' column in the mycollection collection

1 indicates the meaning of displaying this column, and can also be expressed by true

image-20221015155018086

12. Sort by salary in ascending order. (Replace 1 with -1 to sort in descending order)

image-20221015155228573

13. Query the username column and remove duplicate data

image-20221015155326194

Comparison of Where statements in MongoDB and RDBMS:

image-20221015155403664

14. Query data with age less than 13

image-20221015155531962

15. Query the data whose age is equal to 13

image-20221015155632315

16. Query data with age greater than 15

image-20221015155943311

17. Query data not equal to 13

image-20221015160111029

MongoDB AND conditions

MongoDB's find() method can pass in multiple keys, each key separated by commas. The syntax format is as follows:

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

18. Query the data with age equal to 20 and salary equal to 200

image-20221015160414164

19. Query the data whose age is less than 13 and salary is greater than or equal to 200.

image-20221015160734557

MongoDB OR condition

The MongoDB OR conditional statement uses the keyword $or, and the syntax format is as follows:

db.col.find(
	{
    	$or:[
            {key1:value1},{key2:value2}
        ]
    }
)

20. Query data with salary greater than 300 or age less than or equal to 13.

image-20221015161023486

AND and OR used together

21. Query the data whose username is 'banma' or age is 8 when salary is greater than or equal to 300, similar conventional SQL statement

为:where salary>=300 and (username = ‘banma’ or age = 8)

image-20221015161224548

MongoDB $type operator

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

The types that can be used in MongoDB are shown in the following table:

image-20221015161306407

22. Get the data of username in the mycollection collection as String type.

image-20221015161423623

MongoDB regular expressions

Regular expressions use a single string to describe and match a series of strings that conform to a certain syntax rule.

23. Query the data containing 'm' in username.

image-20221015161538597

24. Query data starting with z

image-20221015161638283

Guess you like

Origin blog.csdn.net/weixin_57367513/article/details/132582056