Mongodb database installation configuration, basic operation examples

Time:2020-7-8

This paper describes the mongodb database installation configuration, basic operations. For your reference, the details are as follows:

1. Introduction

No SQL: NoSQL (NoSQL = not only SQL), which means “not only SQL”, is a general term for RDBMS which is different from traditional RDBMS. NoSQL is used for the storage of super large-scale data. These types of data storage do not need fixed mode and can be expanded horizontally without redundant operations.

RDBMS NOSQL
-Highly organized structured data
-Structured query language (SQL)
-Data and relationships are stored in separate tables.
-Data manipulation language
-Strict consistency
-Basic affairs
-It’s not just SQL
-There is no declarative query language
-There are no predefined patterns
-Key value pair storage, column storage, document storage
-Final consistency, not acid property
-Unstructured and unpredictable data
-Cap theorem
-High performance, high availability and scalability

Mongodb is written by C + +, which is an open source database system based on distributed file storage. Mongodb stores the data as a document, and the data structure is composed of key value pairs (key = > value). Mongodb documents are similar to JSON objects, which can easily query embedded objects and arrays in documents. Field values can contain other documents, arrays and document arrays. Data images can be created locally or through the network, which makes mongodb more scalable. If the load increases (requires more storage space and more processing power), it can be distributed on other nodes in the computer network (so-called fragmentation).

2. Installation configuration

1. Download Windows installation package from official website https://www.mongodb.com/download-center#community

2. Click the installation package, install according to the instructions, and select the custom installation location. Note: when I installed version 3.6, the software reported an error and could not complete the installation. After querying, I found that the compass box in the last step of installation was not checked. If you need compass, click the installation program again after installation and select the change option to re install compass.

3. Configure mongodb: create three files in the location you want: data folder (used to store database data), logs\ mongodb.log File (used to store database log), etc\ mongodb.conf File (for related configuration). open mongodb.conf File, input relevant configuration information:

#Database path

dbpath=D:\MongoDB\data

#Log output file path

logpath=D:\MongoDB\logs\mongodb.log

#The error log adopts the append mode. After configuring this option, mongodb's log will be appended to the existing log file instead of creating a new one

logappend=true

#Enable log file, which is enabled by default

journal=true

#This option can filter out some useless log information. If you need to debug, please set it to false

quiet=true

#The default port number is 27017

port=27017

4. Install Mongo service: open the command line in Bin folder under Mongo installation directory, and enter:


mongod --config "D:\MongoDB\etc\mongodb.conf" --install --serverName "MongoDB"

–Config is followed by the address of the configuration file saved just now, – servername followed by the name of the created service

After execution, you can see the mongodb service in the windows 10 search service. Click Start:

Or execute the command line mongod — dbpath.. / data in the mongodb / bin directory to start the Mongo service.

5. Open the command line: configure the environment variables, add the environment variables to the bin folder of mongodb, create a new command line window at any location, and enter Mongo to open the shell command line of Mongo.

3. Basic operation

1. Create / switch to database: use databasename. A new database will not be displayed. It will only be displayed after a record is inserted into it

Delete database:


db.dropDatabase()

2. Create a collection:


db.createCollection('mall')

Delete set Mall:


db.mall.drop()

3. Create users. Create a user for the database Mall:


db.createUser({"user":"root",pwd:"mallroot",roles:[{role:'dbOwner',db:'mall'}]})

4. Import the JSON file into the database. Exit Mongo and execute under CMD:


mongoimport -d mall -c user --file F:\resource\mall-users

Import the mall users file into the users collection of the mall database

5. Insert a record into the collection Mall:

db.mall.insert ({"name": "Xiaomi 6", "price": "2699"})

Just like the JSON format, write the data you want to insert in the form of key value pairs (key = > value).

6. Delete a piece of data:


db.mall.remove({mID:1005})

Delete a piece of data with an ID of 1005. Note that if {mid: “1005”} is of string type during insertion{ mID:1005 }Is of type number

7. Modify a piece of data:

db.mall.update ({Name: "millet 6"}, {$set: {price: "2399"})

In update, modify the value of the second parameter by using the key of $set

8. To view data in a collection:


db.mall.find()

Add. Pretty() after it to format and view the data.

Condition query:


db.mall.find({price:{$lt:2000}})

Query items with price lower than 2000

9. Array operation

The placeholder $represents the subscript of the array. For example, only the elements in the cartlist array that meet the conditions are updated,


user.update({conditions},{
  $set:{"cartList.$.productNum":productNum}
 })

$addtoset: if there is no such data in the array, add the data to the array. If there is the same array in the array, do not add it


user.update({conditions},{
  $addToSet:{cartList:cartItem}
 })

$Pop: delete array data, 1 from the beginning and – 1 from the end


user.update({conditions},{
  $pop:{cartList:1}
 })

$pull: delete the specified data, such as deleting the element of the specified productid in the cartlist array under the specified userid


user.update({userId:userId},{
  $pull:{
   cartList:{productId:productId}
  }
 }

$push: insert an element into the array; $each traverses the array; $sort sorts the array; $slice cuts the array; $position specifies the location of the inserted data.

db.test.update( { _id: 5 },
 { $push: { quizzes: { $each: [ { wk: 5, score: 2 },
                { wk: 6, score: 1 },
                {wk: 7, score: 3}], // traverse insert data
            $sort: {score: - 1}, // in descending order of score
            $slice: 3, // only the first three pieces of data are left after clipping
            $ position:2          // Insert from the second position
           }
      }
 }
 );

I hope that this paper will be helpful to mongodb database program design.

Recommended Today

asp.net Application of regular expression

1. Balanced group / recursive matching (?’ Group ‘), which is called the corresponding content of group, and counts it on the stack;(?’- Group ‘), and count the corresponding content named group out of the stack(?!) Zero width negative look ahead assertion. Since there is no suffix expression, attempts to match always failRegular example:,{0,1}”5″:\[[^\[\]]*(((?’Open’\[)[^\[\]]*)+((?’-Open’\])[^\[\]]*)+)*(?(Open)(?!))\],{0,1} Test […]