Super detailed MongoDB basic operation (theory + example)

One, create a database

use DATABASE_NAME

If the database does not exist, create the database, otherwise switch to the specified database.

Examples:
Insert picture description here
1. The newly created database cannot be displayed using show dbs, and some data needs to be inserted to display it.
2. The default database in MongoDB is test. If you have not created a new database, the collection will be stored in the test database.

Two, delete the database

db.dropDatabase()

Delete the current database, the default is test, you can use the db command to view the current database name.

db: View the current database name

Three, create a collection

db.createCollection(name, options)

Parameter Description:

  • name: the name of the collection to be created
  • options: optional parameters, specify options related to memory size and index

options can be the following parameters:

Field Types of description
capped Boolean (Optional) If true, create a fixed collection. A fixed collection refers to a collection with a fixed size. When the maximum value is reached, it will automatically cover the oldest document. When the value is true, the size parameter must be specified.
autoIndexId Boolean This parameter is no longer supported after 3.2. (Optional) If true, automatically create an index in the _id field. The default is false.
size Numerical value (Optional) Specify a maximum value for the fixed set, that is, the number of bytes. If capped is true, this field also needs to be specified.
max Numerical value (Optional) Specify the maximum number of documents contained in the fixed collection.

Example:
In MongoDB, you don't need to create a collection. When you insert some documents, MongoDB will automatically create a collection.

> db.mycol2.insert({
   
   "name" : "德云"})
> show collections
mycol2

Fourth, delete the collection

db.集合名.drop()

If the selected collection is successfully deleted, the drop() method returns true, otherwise it returns false.

Insert picture description here

Five, insert the document

db.COLLECTION_NAME.insert(document)
or
db.COLLECTION_NAME.save(document)

The data structure of the document is basically the same as JSON. All data stored in the collection is in BSON format.
BSON is a binary storage format similar to JSON, which is short for Binary JSON.

  • save(): If the _id primary key exists, update the data, if it does not exist, insert the data. This method is obsolete in the new version. You can use db.collection.insertOne() or db.collection.replaceOne() instead.
  • insert(): If the primary key of the inserted data already exists,
    org.springframework.dao.DuplicateKeyException will be thrown , prompting that the primary key is duplicated and the current data will not be saved.

1. After version 3.2, the following syntaxes can be used to insert documents:

  • db.collection.insertOne(): Insert a piece of document data into the specified collection
  • db.collection.insertMany(): Insert multiple pieces of document data into the specified collection
# 插入单条数据
> var document = db.collection.insertOne({
   
   "a": 3})
> document
{
"acknowledged" : true,
"insertedId" : ObjectId("571a218011a82a1d94c02333")
}
# 插入多条数据
> var res = db.collection.insertMany([{
   
   "b": 3}, {
   
   'c': 4}])
> res
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("571a22a911a82a1d94c02337"),
ObjectId("571a22a911a82a1d94c02338")
]}

2. Insert multiple pieces of data at once
(1) Create an array first
(2) Place the data in the array
(3) Insert into the collection once

var arr = [];
for(var i=1 ; i<=20000 ; i++){
arr.push({num:i});
}
db.numbers.insert(arr);

Six, update the document

MongoDB uses the update() and save() methods to update the documents in the collection. Next, let us look
at the application of the two functions and their differences in detail .

1. The update() method

Used to update existing documents. The syntax format is as follows:

db.collectio_name.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
})

Parameter Description:

  • query: The query condition of update, similar to the one after where in the sql update query.
  • update: update objects and some of the newer operators (e.g. ,,, inc...), etc., can also be understood as the following set in the sql update query
  • upsert: Optional, this parameter means whether to insert objNew if there is no update record, true is insert, the default is false, not insert.
  • multi: Optional, mongodb defaults to false, and only updates the first record found. If this parameter is true, all multiple records found according to the conditions will be updated.
  • writeConcern: Optional, the level of the exception thrown.
>db.col.insert({
title: 'MongoDB 教程',
description: 'MongoDB 是一个 Nosql 数据库',
by: '德云学院',
url: 'http://www.deyun.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100})

Update the title (title) through the update() method:

db.col.update({‘title’:‘MongoDB 教程’},{$set:{‘title’:‘MongoDB’}})

The above statement will only modify the first document found. If you want to modify multiple identical documents, you need to set the multi parameter to true.

db.col.update({‘title’:‘MongoDB 教程’},{$set:{‘title’:‘MongoDB’}},{multi:true})

2. The save() method

Replace the existing document with the incoming document, update the _id primary key if it exists, and insert it if it does not exist.
The syntax format is as follows:

db.collection_name.save(
<document>,
{
writeConcern: <document>
})

Parameter Description:

  • document: Document data.
  • writeConcern: Optional, the level of the exception thrown.

For example:
replace the document data whose _id is 56064f89ade2f21f36b03136:

db.col.save({
"_id" : ObjectId("56064f89ade2f21f36b03136"),
"title" : "MongoDB",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "Runoob",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"NoSQL"
],
"likes" : 110})

Seven, query documents

db.collection_name.find(query, projection)

  • query: Optional, use query operators to specify query conditions
  • projection: Optional, use the projection operator to specify the return key. When querying, all the key values ​​in the document are returned, just omit this parameter (default omitted).

If you need to read the data in a readable way, you can use the pretty() method, the syntax format is as follows:

db.col.find().pretty()

pretty()Method to display all documents in a formatted way

1. MongoDB conditional operator

$gt -------- greater than >
$gte --------- gt equal >=
$lt -------- less than <
$lte --------- lt equal <=
$ne ----------- not equal !=
$eq -------- equal

2, MongoDB and RDBMS Where statement comparison

operating format example Similar statements in RDBMS
equal {<key>:<value>} db.col.find({"by":"星星点灯"}).pretty() where by ='Rookie tutorial
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
more than the {<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
not equal to {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

3. MongoDB AND conditions

MongoDB's find() method can pass in multiple keys, each key is separated by a comma, which is the AND condition of regular SQL. The syntax format is as follows:
db.col.find({key1:value1, key2:value2}).pretty()
or
db.col.find({‘$and’:[{key1:value1},{key2:value2}]}).pretty()

E.g:

db.col.find({
   
   "by":"星星点灯", "title":"MongoDB 教程"}).pretty()

Similar to the WHERE statement: WHERE by='Star lights' AND title='MongoDB Tutorial'

4、MongoDB OR 条件

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

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

E.g:

db.col.find({‘$or’:[{
   
   "by":"星星"},{
   
   "title": "MongoDB 

5. Combined use of AND and OR

db.col.find({"likes": {$gt:50}, $or: [{"by": "星星点灯"},{"title": "MongoDB 教程"}]}).pretty()

6. Fuzzy query

Search for documents whose title contains the word "教":
db.col.find({title:/教/})

Query the documents whose title field starts with the word "教":
db.col.find({title:/^教/})

Query the documents whose titl e field ends with the word "教":
db.col.find({title:/教$/})

8. Delete documents

The MongoDB remove() function is used to remove the data in the collection. It is a good habit to execute the find() command before executing the remove() function to determine whether the execution conditions are correct. The syntax is as follows:

db.collection_name.remove(
<query>,
<justOne>)
}

Parameter Description:

  • query: (optional) the condition of the deleted document.
  • justOne: (Optional) If set to true or 1, only one document will be deleted. If this parameter is not set or the default value is
    false, all documents matching the conditions will be deleted.

E.g:

db.col.remove({'title':'MongoDB Tutorial'})

If you only want to delete the first found record, you can set justOne to 1, as shown below:

db.collection_name.remove(remove condition, 1)

If you want to delete all data, you can use the following methods:

db.col.remove({})

Guess you like

Origin blog.csdn.net/PILIpilipala/article/details/113818320