1. Basic concepts

Because MongoDB and we commonly used relational database also has a certain connection, here to tell you first, easy to learn by analogy

Relational database MongoDB
The database The database
table A collection of
line The document
column field

(1) Database

A single instance of MongoDB can hold multiple independent databases, which are placed in different files

(2) Set

Collections are collections of MongoDB documents, similar to the concept of tables in a relational database

Collections have no fixed structure, and you can insert different formats and types of data into collections, but usually the data is related to each other

(3) Documents

A document is a set of key-value pairs, similar to the concept of rows in a relational database, with the same data structure as JSON, called BSON

Documents do not need to set the same fields, and the same fields do not need the same data types, but the key-value pairs in the document must be ordered

2. Database operation

The default MongoDB database is test. If you do not create a new database, the collection will be stored in test by default

(1) Create a database

use DATABASE_NAME
Copy the code

If the database exists, switch to the specified database; If the database does not exist, create it

For example, the following command will create the myDB database:

> use myDB
switched to db myDB
Copy the code

(2) Check the existing database

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
Copy the code

Note: The newly created database does not appear in the database list. It will only appear after data is inserted into the newly created database

(3) View the current database

> db
myDB
Copy the code

(4) Delete the database

> db.dropDatabase()
{ "ok" : 1 }
Copy the code

3. Set operation

(1) Create a collection

db.createCollection(
    COLLECTION_NAME,
	{
    	capped: <boolean>,      // Optional. If true, a fixed collection is created, and size must be specified
    	autoIndexId: <boolean>,	// Optional. If true, the index will be automatically created in the '_id' field
    	size: <number>,         // Optional, specify the maximum space (in bytes) that can be used for a fixed collection
    	max: <number>           // Optionally, specify the maximum number of documents to contain for a fixed collection})Copy the code

Note: In MongoDB, the collection is created only after the document is inserted

For example, the following command will create the myCol collection in the myDB database:

> use myDB
switched to db test
> db.createCollection("myCol")
{ "ok" : 1 }
Copy the code

(2) View the existing collection

> show collections
myCol
Copy the code

(3) Delete the set

db.COLLECTION_NAME.drop()
Copy the code

For example, the following command will delete the myCol collection from the myDB database:

> db.myCol.drop()
true
Copy the code

4. Document operation

(1) Insert the document

db.COLLECTION_NAME.insert(document)
Copy the code

Note: If the collection is not in the database, MongoDB will automatically create the collection and insert the document

For example, the following command will insert documents into the myCol collection of the myDB database:

> use myDB
switched to db myDB
> db.myCol.insert({"name":"MongoDB"})
WriteResult({ "nInserted" : 1 })
Copy the code

(2) Query documents

db.COLLECTION_NAME.find(
	query,		// Optional, specify the conditions for querying documents
	projection	// Optional, use the projection operation to specify the key to return. The default omission means that all keys in the document are returned
)
Copy the code

Common search conditions are as follows:

describe The operator format
Is equal to the {<key>:<value>}
Is not equal to $ne {<key>:{$ne:<value>}}
Less than $lt {<key>:{$lt:<value>}}
Less than or equal to $lte {<key>:{$lte:<value>}}
Is greater than $gt {<key>:{$gt:<value>}}
Greater than or equal to $gte {<key>:{$gte:<value>}}
AND conditions {<key1>:<value1>,<key2>:<value2>}
OR conditions $or {$or:[{<key1>:<value1>},{<key2>:<value2>}]}

For example, the following command will query documents whose name field is equal to MongoDB:

> db.myCol.find({"name":"MongoDB"{})"_id" : ObjectId("5c7c069826cb01475e68f64e"), "name" : "MongoDB" }
Copy the code

(3) Update the document

db.COLLECTION_NAME.update(
    query,		// Specify the object to be updated
    update,		// Specify the update object
    {
        upsert: <boolean>,	// Optional, specifies whether to insert updated objects if no updated objects exist. The default is false
        multi: <boolean>,	// This parameter is optional. If true, all eligible records are updated. The default is false
        writeConcern: <document>	// Optional, specify the level of exception to be thrown})Copy the code

For example, the following command will update the data field name in the myCol collection of the myDB database:

> db.myCol.update({"name":"MongoDB"}, {$set: {"name":"MySQL"}})
WriteResult({ "nMatched" : 1."nUpserted" : 0."nModified" : 1 })
Copy the code

(4) Delete the document

db.COLLECTION_NAME.remove(
    query,	// Specify the object to be deleted
    {
        justOne: <boolean>,      // Optional. If true, only one document will be deleted. The default is false
        writeConcern: <document> // Optionally, define the level at which an exception is thrown})Copy the code

For example, the following command will delete documents in the myDB database where the myCol collection name field is equal to MySQL:

> db.myCol.remove({"name":"MySQL"})
WriteResult({ "nRemoved" : 1 })
Copy the code