Operate the mongdb database

The mongodb website
https://www.mongodb.com/try/download/community  enters and pulls down to see


Operate mongodb 
1. Configure environment variables Enter the computer configuration environment variable D:\mono\bin\bin so that it can be accessed globally

Table of contents

1 Connect to the database

Enter cmd, open the command prompt window, enter mongo, and enter the database.

​edit

2 Create a database

3 View database

 4 Delete the database

5 Create/delete/display collections

After deleting the database in the previous step, the student database is gone, so create it again to complete the following operations.

6 Insert document

7 Update Documentation

8 Query documents

9 Delete documents

10 MongoDB data collection export and import

1 Connect to the database

Enter cmd, open the command prompt window, enter mongo, and enter the database.

mongo

2 Create a database

Operation statement:

use DATABASE_NAME

 DATABASE_NAME is the name of the database, if the database exists, switch to the database; if the database does not exist, create the database.

3 View database

Operation statement:

show dbs

 This command can check which databases are available. But the student database just created is not displayed, because some data needs to be inserted into the student database to display.

db.student.insert({"_id":"001"})

Notice: 

To rename a collection in MongoDB, use renameCollection(). Let's create a collection with documents -

db.student.renameCollection("demo");

 

 To view the current database, the operation statement:

db

 Statistical information in the database, operation statement:

db.stats

 4 Delete the database

db.dropDatabase()

5 Create/delete/display collections


After deleting the database in the previous step, the student database is gone, so create it again to complete the following operations.

In a relational database, there is a database, a data table, and each row of data in the table. And mongodb is a non-relational database. It has databases, collections, and documents, which correspond to the database, data table, and row-by-row data in the relational type. In mongodb, documents form collections, and collections form databases.

Operation command:
 

db.createCollection(name, options)

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

To delete a collection, the operation statement:

db.name.drop()

name: the name of the collection to be deleted

The drop() method returns true if the selected collection is dropped successfully, otherwise it returns false.

 Display the collection under the database, the operation statement:

show collections

In MongoDB, you don't need to create collections. MongoDB automatically creates collections when you insert some documents.

6 Insert document

Operation statement:

//方法1
db.COllECTION_NAME.insert(document)
//方法2
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, and it is the abbreviation of Binary JSON.
1. save(): If the _id primary key exists, update the data, and 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.
2. insert(): If the primary key of the inserted data already exists, an org.springframework.dao.DuplicateKeyException will be thrown, prompting that the primary key is duplicated, and the current data will not be saved. ,
 

 After version 3.2, the following syntaxes are available for inserting documents:

db.collection.insertOne():向指定集合中插入一条文档数据
db.collection.insertMany():向指定集合中插入多条文档数据

 Example: Insert a single row of data

# 首先输入以下语句
var document = db.collection.insertOne({ "a": 2 })
# 敲击回车后输入以下语句
document

 Example: inserting multiple rows of data

# 首先输入以下语句
var res = db.collection.insertMany([{ "b": 3 },{ "c": 4 }])
# 敲击回车后输入以下语句
res

 Insert multiple pieces of data at a time:
(1) create an array first
(2) put the data in the array
(3) insert into the collection once

 Example: Insert multiple statements at once

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

7 Update Documentation

MongoDB uses update() and save() methods to update documents in a collection. Next, the application of the two functions and their differences are introduced in detail.

1. 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>
   }
)

query: query condition of update, similar to where in sql update query.
update: The update object and some update operators (such as $, $inc...), etc., can also be understood as upsert after the set in the sql update query
: optional, this parameter means that if there is no update record, Whether to insert objNew, true means insert, default is false, no 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 condition are updated.
writeConcern: optional, the level of exception thrown.
 

db.col.insert({
    title: 'MongoDB数据库',
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '青阳子',
    url: 'http://www.baidu.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

 

Update the title with the update() method:

db.col.update({"title":"MongoDB数据库"},{$set:{"title":"MongoDB我喜爱的数据库"}})

 The above statement will only modify the first found document. 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. save() method: replace the existing document with the incoming document, update if the _id primary key exists, and insert 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 exception thrown.

For example: replace the document data with _id 56064f89ade2f21f36b03136

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

8 Query documents

Operation statement:

db.collection_name.find(query, projection)

query: optional, use the query operator to specify the query condition
projection: optional, use the projection operator to specify the returned key. When querying, all key values ​​in the document are returned, just omit this parameter (default omission).

db.col.find()

If you need to read data in an easy-to-read way, you can use the pretty() method, the syntax is as follows:

db.col.find().pretty()

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

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

For example:

db.col.find({'$or':[{"by":"青阳子"},{"title": "MongoDB"}]}).pretty()

 4. Combination of AND and OR

db.col.find({"likes": {$gt:50}, $or: [{"by": "青阳子"},{"title": "MongoDB"}]}).pretty()

5. Fuzzy query
1. Query documents whose title contains the word "Mon":

db.col.find({title:/Mon/})

 2. Query the documents whose title field starts with "jiao":

db.col.find({title:/^Mon/})

3. Query the documents whose title field ends with the word "teach":

db.col.find({title:/教$/})

9 Delete documents

The MongoDB remove() function is used to remove data from a 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>)
}

query : (optional) The criteria for the deleted documents.
justOne : (optional) If set to true or 1, only one document will be deleted, if not set, or use the default value of false, all documents matching the condition will be deleted.

db.col.remove({'title':'MongoDB数据库'})

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

db.collection_name.remove(删除条件,1)

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

db.col.remove({})

10 MongoDB data collection export and import

Export (mongoexport) 
export data command: mongoexport -h dbhost -d dbname -c collectionName -o output

-h : database address, the IP and port where the MongoDB server is located, such as localhost:27017

-d : Specify the database instance used, such as test

-c specifies the collection to be exported, such as c1

-o specifies the name of the file to be exported, such as E:/wmx/mongoDump/c1.json. Note that it is a file rather than a directory. If the directory does not exist, it will be created together. It also uses  mongoexport in the bin directory of the
installed  MongoDB directory. exe and mongoimport.exe 

 As shown below, mongoexport -h localhost:27017 -d mydb1 -c c1 -o E:/wmx/mongoDump/c1.json will export the collection c1 under the database mydb1 to the E:/wmx/mongoDump/c1.json file, Storage files can be in various forms, such as txt, xls, docs, etc.
 

C:\Users\Administrator>mongoexport -h localhost:27017 -d manager -c users -o D:/json/users.json
2018-09-12T16:42:07.297+0800    connected to: localhost:27017
2018-09-12T16:42:07.379+0800    exported 100 records
 
C:\Users\Administrator>mongoexport -h localhost:27017 -d manager -c users -o D:/json/users.txt
2018-09-12T16:42:58.225+0800    connected to: localhost:27017
2018-09-12T16:42:58.311+0800    exported 100 records
 
C:\Users\Administrator>

Data export was successful.

Import (mongoimport)
import data command: mongoimport -h dbhost -d dbname -c collectionname file address...

-h : Database address, the IP and port where the MongoDB server is located, such as localhost:27017

-d: specify the library used, specify the database instance used, such as test

-c : Specify the collection to be imported, such as c1, c2, which may be inconsistent with the export, just customize it, and create it directly if it does not exist.

mongoimport -h localhost:27017 -d stu_info -c collection  D:/json/users.json

Guess you like

Origin blog.csdn.net/qq_34093387/article/details/128330637