Mongo introduction#

MongoDB is an open source document database based on distributed file storage. Written in C++ language. Designed to provide high performance, high availability and high scale data storage solutions for WEB applications.

Mongo advantages

Mongo advantages

MongoDB Application Scenarios#

  • Data cache

    Because of its high performance, MongoDB is suitable as a caching layer for information infrastructure. After the system restarts, the persistent cache layer built by MongoDB avoids overloading the underlying data source.

  • Object and JSON storage

    MongoDB’s BSON(binary JSON) data format is very suitable for document format storage and query, and JSON format storage is the most close to the real object model, friendly to developers, convenient rapid development iteration, flexible mode lets you not to constantly change the database field and structure.

  • High scalability scenario

    MongoDB enables the horizontal expansion of MongoDB service capability through sharding cluster.

  • Weak transaction type business

    MongoDB does not support multi-document transactions, so applications such as banking systems that require a large number of atomically complex transactions are not suitable for MongoDB. (Note: MongoDB 4.0 will support transactions across documents).

This section describes features of the mongodb version

Directing a concept#

Through the comparison with the relational database mysql, let us more easily understand some concepts of MongoDB

Directing a concept Relational database (SQL) concepts instructions
database database The database
table collection Database tables/collections
row document Data line/document
column filed Data fields/fields
index index The index

MongoDB data relationship diagram

The database#

  • Multiple databases can be created in one MongoDB.

  • The default MongoDB database is DB, which is stored in the data directory

A collection of#

  • The collection name cannot start with system

  • The format of each row in a table in a relational database is agreed in advance, while the format of documents in a collection in MongoDB is not fixed, that is to say, we can insert the following data into a unified document.

{" site ":" www.wuhuan.me "} {" site ":" www.baidu.com ", "name" : "baidu"}Copy the code

The document#

  • The values in the document can be not only strings inside double quotes, but also several other data types (or even the entire embedded document)

For example, in a relational database, there is a table for students and a table for course. The table structure and data are as follows:

Students table

id name sex age
1 Li lei 0 12
2 Han meimei 1 12

Course table

id course_id course_name score user_id
1 1 Chinese language and literature 99 1
2 2 mathematics 100 1
3 1 Chinese language and literature 96 2
4 2 mathematics 98 3

The above data and structures can be expressed in MongoDB using embedded documents (one-to-many) :

{" _id ": ObjectId (" 5349 b4ddd2781d08c09890f3"), "name" : "li lei", "sex" : "0", "age" : "12", "course" : [{" course_id ": 1, "Course_name" : "language", "score" : 99}, {" course_id ": 2," course_name ":" mathematics ", "score" : 100, }]} {" _id ": ObjectId (" 5349 b4ddd2781d08c09890f4"), "name" : "han meimei", "sex" : "1", "age" : "12", "course" : [{" course_id ": 1, "Course_name" : "language", "score" : 96}, {" course_id ": 2," course_name ":" mathematics ", "score" : 98,}]}Copy the code
  • The key/value pairs in the document are ordered, and the keys in the document are non-repeatable and case sensitive.

The data type#

The data type describe
String A string. Data types commonly used to store data. In MongoDB, utF-8 encoded strings are valid.
Integer Integer value. Used to store values. Depending on the server you use, it can be 32-bit or 64-bit.
Boolean Boolean value. Used to store Boolean values (true/false).
Double A double precision floating point value. Used to store floating point values.
Min/Max Keys compares a value to the lowest and highest values of a BSON (binary JSON) element.
Array Use to store an array or list or multiple values as a key.
Timestamp The time stamp. Record the time when the document was modified or added.
Object For inline documents.
Null Used to create null values.
Symbol Symbols. This data type is basically the same as a string type, except that it is generally used in languages that use special symbolic types.
Date Date time. Store the current date or time in UNIX time format. You can specify your own Date and time by creating a Date object and passing in the year, month and day information.
Object ID Object ID. The ID used to create the document.
Binary Data Binary data. Used to store binary data.
Code Code type. Used to store JavaScript code in documents.
Regular expression Regular expression type. Used to store regular expressions.

ObjectId#

MongoDB documents must have a default _id key and the _id is always unique within a collection. The value of the _ID key can be any type, and the default is an ObjectId object, which is automatically created by the MongoDB database. The main reason MongoDB used objectId instead of the normal practice of auto-adding primary keys was that it was laborious and time-consuming to automatically add primary keys in a (distributed) synchronization across multiple servers.

The ObjectId consists of 12 bytes of BSON

  • The first four bytes represent the timestamp

  • The next three bytes are the machine id

  • The next two bytes consist of the process ID (PID)

  • The last three bytes are random numbers.

Create a new ObjectId

You can create a new ObjectId from the command line with the following statement

> newId=ObjectId()
Copy the code

The above statement will return a unique _ID

ObjectId("1249b4ddd2712d08c09890f3")
Copy the code

You can also replace the ObjectId automatically generated by MongoDB with the generated ObjectId.

Basic Usage of MongoDB#

Installing the Database#

Installing MongoDB on Windows is relatively easy. Download the corresponding Windows installation package at the MongoDB download address on the official website and install it with one click.

After the installation, add the bin directory in the MongoDB installation directory to the environment variables of the system.

Start the database#

Start the database using the mongod command

  • Method 1: Start in common mode
> mongod --dbpath E:\MongoDB\data\db # Add --port=[port number] if default port is not usedCopy the code

E:\data\db is the path of the data file

  • Method 2: Start the system using the configuration file
> mongod --config E:\MongoDB\mongo.conf
Copy the code

E:\MongoDB\mongo.conf is the path of the configuration file. The content of the configuration file is:

Data file path dbpath=E:\mongondb\data\db # Log file path logpath=E:\mongondb\log\mongon Logappend =true # Noauth =true without any authenticationCopy the code

Connecting to a Database#

The standard syntax for connecting a database to a URL using Mongo [, link string] is as follows

mongodb://[username:password@]host[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Copy the code
  • Log in to the local default database server, no user name password, default port 27017, connect to the default DB database
> mongo mongodb://localhost/db 
Copy the code

or

> mongo 
Copy the code
  • Use user name admin and password 123456 to log in to the test database whose local port is 27017.
> mongo mongodb://admin:123456@localhost:27017/test
Copy the code

Creating a database#

To create a database, use [database name], for example, to create a database on test123

> use test123
switched to db test123
> db
test123
Copy the code

To display all the current databases, run the show DBS command

> show dbs
db     0.001GB
local  0.000GB
Copy the code

Where is the test123 we just created? Insert db.[set name]. Insert (json format data object) into test123.

> show dbs
db     0.001GB
local  0.000GB
> use test123
switched to db test123
> db
test123
> db.coll.insert({"title":"not data!"})
WriteResult({ "nInserted" : 1 })
> show dbs
db       0.001GB
local    0.000GB
test123  0.000GB
Copy the code

Look at db.[Collection name].find() for the data you just added

> use test123
switched to db test123
> db.coll.find()
{ "_id" : ObjectId("5a66e39914fea5f8ff237420"), "title" : "not data!" }
Copy the code

Run the use command to create a database if the database does not exist, and switch to the specified database if the database exists.

Deleting a Database#

Drop the database using the db.dropDatabase() function

Start by looking at all the databases

> show dbs
db       0.001GB
local    0.000GB
test123  0.000GB
Copy the code

Then switch to the database test123 that you want to delete

> use test123
switched to db test123
Copy the code

Deleting the current database

> db.dropdatabase () {"dropped" : "test123", "ok" : 1Copy the code

Data increase#

Data addition methods: insert(),insertOne(),insertMany()

Add a piece of data

Insert / * * * * / > db () method. The person. The insert ({name: "zhang", the age: 18, sex: "male"}); WriteResult({ "nInserted" : 1 }) > db.person.find() }); {"_id" : ObjectId(" 5a7941C65f6D5986321C8416 "), "name" : "Zhang Three ", "age" : 18, "sex" : InsertOne "male"} / * * * * () method inserts a data / > db person. InsertOne ({name: "zhang", the age: 18, sex: "male"}); { dered:true}) "acknowledged" : true, "insertedId" : ObjectId("5a7965855f6d5986321c8422") } > db.person.find() { "_id" : ObjectId("5a7965855f6d5986321c8422"), "name" : "> < span style =" max-width: 100%;Copy the code

Adding Multiple Pieces of Data

The first method is to place the data to be inserted into an array for batch insertion

Insert / * * * * / > db () method. The person. The insert ([{name: "zhang", the age: 18, sex: "male"}, {name: "bill", the age: 21, sex: "female"}, {name: "detective", the age: 20, sex: "male"}, {name: "Daisy", the age: 19, sex: "female"}, {ordered: true}) BulkWriteResult ({" writeErrors ": [ ], "writeConcernErrors" : [ ], "nInserted" : 4, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : InsertMany []}) / * * * * / > () method of the person. InsertMany ([{name: "zhang", the age: 18, sex: "male"}, {name: "bill", the age: 21, sex: "female"}, {name: "detective", the age: 20, sex: "male"}, {name: "Daisy", the age: 19, sex: "female"}, {{ordered: true}) "" acknowledged" : true, "insertedIds" : [ ObjectId("5a7969ec5f6d5986321c8430"), ObjectId("5a7969ec5f6d5986321c8431"), ObjectId("5a7969ec5f6d5986321c8432"), ObjectId("5a7969ec5f6d5986321c8433") ] }Copy the code

{ordered:true} is added to order inserts. Ordered inserts will return when an exception occurs and will not continue to insert the rest of the document in the array. Without this parameter or {ordered:false} is an unordered insert, which will continue if an exception is encountered

Method 2 Add data in batches using blUK objects

  • Step 1: Initialize a batch operation object
    var bulk = db.person.initializeUnorderedBulkOp();
    Copy the code
  • Step 2: Add the data to the BULK object

    Bulk. insert({name:" 6 ",age:19,sex:" female "}); Bulk. insert({name:" 6 ",age:19,sex:" female "}); Bulk. insert({name:" 6 ",age:19,sex:" female "});Copy the code
  • Step 3: The actual method to add to the database

bulk.execute();
Copy the code

You can also insert documents using db. collection name. save(document) command. The save() method is similar to the INSERT () method if the _ID field is not specified. If the _id field is specified, the _id data is updated.

Insert () can insert either an array or an object, insertOne() can insert only one object, insertMany() can insert only one array, insert() returns the number of successful inserts, The insertOne() and insertMany() methods return a success flag and the _objectId of a successful insert

Data query#

Query commands: find(), findOne()

The result of the findOne() query is already formatted, and the find() method can do the same for formatting the output by calling pertty() to decorate the query.

Example: db.person.find({age:18}) queries all information about a person whose age is 18

Example: db.person.find({age:{$gt:18}},{name:1,sex:1}) query the name and gender of persons older than 18 in the database

$lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}; $lt = {name:1,sex:1}

Modify query methods: limit(),sort(),skip(),pretty()

For example: db.person.find({age:{$gt:18}},{name:1,sex:1,age:1}).sort({age:-1}).limit(3).skip(1).pretty() Query the name and gender of all persons older than 18 in the PERSON set of the DB database, and then sort them in descending order by age, and then take the first three of the sorted data, and then skip the next set of data

Sort ({age:-1}) sort({age:-1}) sort({age:-1})

To delete data#

Remove (), drop()

Remove () and drop() methods

Remove ({}) The remove method passes a null object, which deletes all documents in the PERSON collection of the DB database, but does not delete the index

For example: db.person.drop() will drop all documents in the PERSON collection in the DB database, and will also drop all indexes in the Person collection. More efficient.

2. Delete the documents that match the conditions

Remove ({name:” person “}) remove all documents from the person set in the DB database whose name is equal to person.

3. Delete a record

Db.person. remove({name:” zhangsan “},{justOne:true}); Db.person. remove({name:” person “},1);

Delete only one document that matches the criteria

Data modification#

Update method: update()

Db.person. update({name:” person “},{$set:{age:19}}) update({name:” person “},{$set:{age:19}}

Db.person. update({name:” person “},{$set:{age:”123456”},$currentDate: {lastModified: True}}) adds a last modified time field to the currently modified document

Db.person. update({name:” person “},{$set:{age:20},$currentDate: {lastModified: True}},{multi:true}) by default, only one document that meets the condition is modified. If multiple documents meet the condition and need to be modified, you only need to add the third parameter {multi:true} to modify multiple documents.

4. Examples of upsert options: Db.person. update({name:” person “},{name: “person”,age:20,sex:” man “},{upsert:true}) If {upsert:true} is added, it will insert a new document if no matching document is found.

Note: MongonDB automatically changes the original data type in the document according to the data type when modifying the data. For example, if the age of a document is numeric, you pass the age in a string when modifying the record, and the age field in the document becomes a string type.

The index#

Indexes can greatly improve query efficiency, just like book directories. If there is no index, mongodb will scan every file in the collection and select the data that meets the query conditions. In the case of large amount of data, this query rate is very low

Get the collection index using db.collection name.getIndexes ()

> db. Person. GetIndexes () [{/ / person set the default index "v" : 1, / / ascending "key" : {" _id ": 1} / / index column," name ": "_id_", // index name "ns" : "test.person" // specify set}]Copy the code

Create indexes

CreateIndex createIndex()

Example: db.person.createIndex({“name”:1}) creates an ascending index for the name field in the Person collection

> db. Person. GetIndexes () [{/ / the default index "v" : 1, "key" : {" _id ": 1}," name ":" _id_ ", "ns" : "The test. The person"}, {/ / the newly created index "v" : 1, "key" : {" name ": 1}," name ":" name_1 ", "ns" : "test. The person"}]Copy the code

Remove the index

DropIndex () Example: db.person.dropIndexes({” name “:1})

> db. Person. GetIndexes () / / query index [{" v ": 1," key ": {" _id" : 1}, "name" : "_id_", "ns" : "test. The person"}, {" v ": 1, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "Test.person"}] > db.person. DropIndex ({"name":1}) // Delete {" nIndexesWas" : 2, "ok" : 1} > db. Person. GetIndexes () / / query index [{" v ": 1," key ": {" _id" : 1}, "name" : "_id_", "ns" : "test. The person"}]Copy the code

To delete all indexes, run the dropIndexes() command. Example: db.person.dropindexes ()

> db. Person. GetIndexes () / / query index [{" v ": 1," key ": {" _id" : 1}, "name" : "_id_", "ns" : "test. The person"}, {" v ": 1, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "Test.person"}] > db.person.dropIndexes() {"nIndexesWas" : 2, "MSG" : > db.person.getIndexes() [{"v" : 1, "key" : {" id" : 0, 0, 0, 0, 0, 0] 1 }, "name" : "_id_", "ns" : "test.person" } ]Copy the code

Delete all indexes: index whose name is not _id_ (default index)

Export data file#

Mongodump -h IP --port Port number -u username -p password -d database -o File pathCopy the code
  • If there is no user, drop -u and -p.
  • If you export to the local database, you can remove -h.
  • If the port is the default port, you can deselect – port.
  • If you want to export all databases, you can remove -d.

Export all data from the database

Mongodump -h 127.0.0.1 -o E:\mongondb\dumpCopy the code

Import data file#

Mongorestore -h IP --port port -u username -p password -d database --drop Directory where the file existsCopy the code

– Drop: Deletes all records and then restores them.

Import all databases

> mongorestore E:\mongondb\dump 
Copy the code

Import the test123 database

> mongorestore -d user E:\mongondb\dump\test123 #test123 backup path to this databaseCopy the code







If this article is wrong, please feel free to comment!

Original title:
Basic knowledge of mongodbOriginal link:
www.wuhuan.me/2018/01/22/…

Copyright statement: free reprint – not commercial – not derivative – keep the signature and the original link | Creative Commons BY – NC – ND 3.0