[quick start MongoDB] introduction, installation, core concepts and basic operation

Official documents in English: https://docs.mongodb.com/manual/
MongoDB Chinese website: MongoDB Chinese website | MongoDB Chinese documents

brief introduction

MongoDB is a document database designed to facilitate application development and expansion.

MongoDB is a document database designed for ease of application development and scaling.

MongoDB is a non relational database, but it has rich functions, much like a relational database. The data structure it supports is very loose. It is a JSON like BSON format, so it can store more complex data types.

The query language supported by MongoDB is very powerful. Its syntax is a bit similar to the object-oriented query language. It can almost realize most functions similar to the single table query of relational database, and also supports the establishment of index on data.

characteristic:

  • For collection storage, it is easy to store data of object type
  • Support query and dynamic query
  • Support RUBY, PYTHON, JAVA, C + +, PHP, c# and other languages
  • The file storage format is BSON (an extension of JSON)
  • Support replication and failover and fragmentation
  • Support transaction support
  • Index, aggregate, Association

Application scenario:

  • Game application: use the cloud database MongoDB as the database of the game server to store user information. Users' game equipment and points are directly stored in the form of embedded documents, which is convenient for query and update.
  • Logistics application: use the cloud database MongoDB to store the order information. The order status will be updated continuously during transportation. It is stored in the form of embedded array of cloud database MongoDB. All changes of the order can be read out in one query, which is convenient, fast and clear at a glance.
  • Social application: use the cloud database MongoDB to store user information and circle of friends information published by users, and realize the functions of nearby people and places through geographical location index. Moreover, the cloud database MongoDB is very suitable for storing chat records because it provides very rich queries and is relatively fast in writing and reading.
  • Live video: use the cloud database MongoDB to store user information, gift information, etc.
  • Big data application: use the cloud database MongoDB as the cloud storage system of big data to extract and analyze data at any time and master the dynamics of the industry.

Installing using Docker

Traditional installation methods: download the installation package, decompress and configure environment variables... This method is not used here.

Install using Docker:

# 1. Pull mongodb image
docker pull mongo:5.0.5

# 2. Run mongo image
docker run -d --name mongo -p 27017:27017 mongo:5.0.5

# 3. Enter mongo container and bc6c is the container id
docker ps # View container id
docker exec -it bc6c bash # Enter container terminal

Docker instruction reference: Docker container usage | rookie tutorial (runoob.com)

Core concept

reference resources: MongoDB concept analysis | rookie tutorial (runoob.com)

SQL terms / conceptsMongoDB terms / conceptsExplanation / explanation
databasedatabasedatabase
tablecollectionDatabase tables / sets
rowdocumentData record line / document
columnfieldData field / field
indexindexIndexes
table joinsTable connection, not supported by MongoDB
primary keyprimary keyPrimary key, MongoDB will automatically_ Set the id field as the primary key

Database database

RDB (Relational Database): relational database

The library in MongoDB is similar to the concept of Library in RDB. It is used to isolate different application data through different libraries.

Multiple databases can be established in MongoDB. Each database has its own set and permissions, and different databases are placed in different files.

The default database is "test", and the database is stored in the data directory specified for startup.

Collection collection

Collection is the document group of MongoDB, which is similar to the concept of table in RDB.

Collections exist in the database. Multiple collections can be created in one library. Each set has no fixed structure, which means that different formats and types of data can be inserted into the set, but usually the data we insert into the set will have a certain correlation.

Document

A document is a set of key value pairs (that is, BSON).

MongoDB documents do not need to set the same fields, and the same fields do not need the same data type.

The above point is very different from relational database, and it is also a very prominent feature of MongoDB.

A simple example as like as two peas (JSON).

{"user": "001", "name":"Zhang San", "age": "15"}

basic operation

library

MongoDB creating database | rookie tutorial (runoob.com)

MongoDB delete database | rookie tutorial (runoob.com)

There are three reserved libraries in MongoDB by default:

  • admin

    From the perspective of permissions, this is the "root" database.

    If a user is added to the database, the user automatically inherits the permissions of all databases.

    Some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server.

  • local

    This data will never be copied and can be used to store any collection limited to a local single server.

    That is, the data stored in this library is only visible to the current server and cannot be obtained by other servers.

  • config

    When Mongo is used for sharding settings, the config database is used internally to save information related to sharding.

# Displays a list of all libraries
show dbs # Short for show databses

# Displays the current database object
db

# Connect to the specified database (create if none)
use mydb

# Insert data into mydb Library
db.mydb.insert({"name", "lzy"})

# Delete the current library
db.dropDatabase()

After using use to create a library, show dbs can't be seen directly, because MongoDB doesn't display libraries without data.

aggregate

MongoDB create collection | rookie tutorial (runoob.com)

MongoDB delete collection rookie tutorial (runoob.com)

# View all collections in the library
show collections
show tables
# Create collection
db.createCollection('users')

db.createCollection(name, [options]), options can be the following parameters:

fieldtypedescribe
cappedBoolean(optional) if true, a fixed collection is created. It means that the oldest set of documents will be automatically overwritten when it reaches a fixed size. When the value is true, the size parameter must be specified.
sizenumerical value(optional) specify a maximum number of bytes for the fixed set.
This field must be specified if capped is true.
maxnumerical value(optional) specifies the maximum number of documents contained in a fixed collection.
# If you insert some documents without creating a collection first, MongoDB will automatically create a collection.
db.teachers.insert({"name" : "zhangsan"})
# Deletes the specified collection
db.teachers.drop() 	# Delete the teachers collection
db.users.drop() 		# Delete users collection

file

Query all documents in a collection:

# Query all documents in a collection
db.users.find() # Query the data of users collection

insert

MongoDB insert document | rookie tutorial (runoob.com)

Every document in MongoDB has a_ id as the unique identification.

_ id will be generated automatically by default. If it is specified manually, the manually specified value will be used as the default value_ The value of the id.

  • Insert a single document
# Insert a single piece of data into the users collection
db.users.insert({"name": "zhangsan", "age": 23})
  • Insert multiple documents
# Insert multiple pieces of data into the users collection
# Insert or insertMany can be used to insert multiple items
db.users.insert([
  	{"name":"lisi", "age":16},
  	{"name":"wangwu", "age":18}
])
  • JS script insertion
for (let i = 0; i < 3; i++) {
	db.users.insert({_id: i, name: 'user' + i, age: i+10});
}
# Note that only the last inserted record will be displayed after the script is executed, so it is 1
# WriteResult({ "nInserted" : 1 })

delete

MongoDB delete document rookie tutorial (runoob.com)

# grammar
db.Set name.remove(
   <query>, # Optional, delete condition
   {
     justOne: <boolean>, # Optional. The default value is false to delete all matching documents. If it is true or 1, only one document will be deleted
     writeConcern: <document> # Optional, the level of exception thrown
   }
)
# To delete all documents in the collection, the empty condition must be transferred to {}, and cannot be left blank
> db.users.remove({})

# Delete_ Document with id 1
> db.users.remove({_id: 1})

# Delete_ id is automatically generated data
> db.users.remove({_id: ObjecteId("61fd0addc2df889b4ad70789")}})

to update

MongoDB update document rookie tutorial (runoob.com)

# grammar
db.collection.update(
   <query>, # query criteria
   <update>, # Update content, you can write objects or operators
   {
     upsert: <boolean>, # Optional. By default, false does not exist or insert. If it is true, insert if it does not exist
     multi: <boolean>, # Optional. The default is false, and only the first item is updated. If it is true, all the items queried will be updated
     writeConcern: <document> # Optional, the level of exception thrown
   }
)
# By default, all eligible documents will be updated to subsequent documents, which is equivalent to deleting and then inserting (_id will be retained)
> db.users.update({age: 12},{age: 28})
# before:	{ "_id" : 2, "name" : "user2", "age" : 12 }
# after:	{ "_id" : 2, "age" : 28 } # name is missing

# Use $set to keep the original data for updating
> db.users.update({name: "user1"}, {$set: {name: "User 1"}})
# before:	{ "_id" : 1, "name" : "user1", "age" : 23 }
# after: 	{ "_id" : 1, "name" : "User 1", "age" : 23 } # Other fields are reserved

# Keep the original data and update only the first qualified data
> db.users.update({age: 23}, {$set: {age: 25}}, {multi: false})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# Keep the original data and update all data that meet the conditions (you must use $set)
> db.users.update({age: 23}, {$set: {age: 25}}, {multi: true})
WriteResult({ "nMatched" : 9, "nUpserted" : 0, "nModified" : 9 })

# Keep the original data, update all data that meet the conditions, and insert when there is no data
> db.users.update({name: 'Xiaobai'}, {$set: {name: 'Xiao Hei'}}, {upsert: true})
$WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("61fd18ba88455f04936fe1e1")
})

Keywords: Database MongoDB nosql

Added by EY on Fri, 04 Feb 2022 14:38:20 +0200