Mongdb installation and use


MONGDBInstallation and use

Let’s review what we shared last time:

  • How to uselogpackage
  • logPackage principle and Implementation
  • Custom log

If you are still interested in go’s log package, you can check the articleHow to play go’s log?

Let’s play a simple game todaymongodbInstallation and use of

Mongdb installation and use


MongoDBIs a database based on distributed file storage

useC++Language writing

MongoDBIt mainly provides scalable high-performance data storage solutions for web applications

Yes / no relational database has the most abundant functions. It supports very loose data structure, which is similarJSONofBSONFormatted

MONGODBThe syntax of is a bit similar to the object-oriented query language, and it is also very simple for us to use

Mongdb installation and use


downloadmongodbInstallation package


Multiple systems can be downloaded on the official websitemongdbInstallation package,windowscentosubuntuWait, as shown in the figure

Mongdb installation and use

According to the content on the page, we can choose different versions and ask for them on demand. By default, we will be crab eaters and go directly to the latest version

Mongdb installation and use


decompressionmongodbCompressed package

tar xvf mongodb-linux-x86_64-rhel80-4.4.4.tgz

Rename the extracted directory tomongodb, and move to/usr/locallower

mv mongodb-linux-x86_64-rhel80-4.4.4.tgz mongodb
mv mongodb /usr/local/

get intomongodbDirectory

  • Create data directory
  • Create DB directory under data directory
  • Create a log directory under the data directory
mkdir data
cd data
mkdir db
mkdir log

go back tomongoDirectory, createmongodbYour profile,mongodb.conf, required for subsequent startup

Need inmongodb.confLower configuration

  • dbpath

Data storage location of database

  • logpath

Log file storage location

  • logappend

Is the log appended

  • port

Port number

  • auth

Is certification required

  • fork

Run as a daemon

  • bind

    Restrictions on remote accessip, you can write without restrictions0.0.0.0


takemongodbThe executable program is written to / etc / profile, which will be read automatically when starting up

export MONGODB_HOME=/usr/local/mongodb


mongod -f /usr/local/mongodb/mongodb.conf

About firewall

  • You can directly close the firewall of the system
  • The firewall opens port 27017 to allow clients to connect mongdb

aboutMONGODBStatus view of


ps aux |grep mongodb

View port

netstat -antp |grep 27017


There are the following two operations. You can choose what you like and use what you like

Mongdb installation and use

  • Kill with the kill commandPIDthat will do
  • mongod -f /usr/local/mongodb/mongodb.conf --shutdown

mongodbSet role, user name and password

  • /usr/local/mongodb/mongodb.confThe configuration is as follows, can weauthSet asfalseauthWhen the field is enabled, authentication is enabled, and when it is closed, authentication is closed

Mongdb installation and use

  • mongodbThere are multiple roles
user read、readWrite
administrators dbAdmin、dbOwner、userAdmin
Cluster Administrator clusterAdmin、clusterManager、clusterMonitor、hostManager
Backup and restore permissions backup、restore
All database permissions readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
Super user root
Internal role __system

mongodbUse of database

Select database

use xxx

Create administrator account


After execution, the following effects are obtained:

Successfully added user: {
        "user" : "admin2",
        "roles" : [
                        "role" : "readWriteAnyDatabase",
                        "db" : "admin"

Next, specificmongodbDatabase operation, you can watch the rookie tutorial to learn a wave, which will be used soon…

Mongdb installation and use

mongodbSet startup

  • Add amongodbYour service has arrivedinit.din

    vim /etc/rc.d/init.d/mongod
  • Write a concrete implementation of this service
start() {
    /usr/local/mongodb/bin/mongod  --config /usr/local/mongodb/mongodb.conf

stop() {
    /usr/local/mongodb/bin/mongod --config /usr/local/mongodb/mongodb.conf --shutdown
case "$1" in


 echo  $"details: $0 {start|stop|restart}"
 exit 1
  • Add execution permission to the executable of this service
chmod +x /etc/rc.d/init.d/mongod
  • start-upmongod
service mongod start
  • closemongod
service mongod stop
  • restartmongod
service mongod restart

Visualization tools

Introduce a visualization tool, very easy to use, better thannosqlThis tool is much easier to use

Robo 3T 1.3.1The download link is as follows

The software operation is relatively simple. After you download it, you can get familiar with the interface and use it.

Mongdb installation and use

GOLANGSimple operationmongodb

mongodbThere are two kinds of drivers that we use more:

  • mongodbThe official library,
  • Third party

    The address is:

We use the official driver library to introducemongdbordinary

  • increase
  • Delete
  • change
  • check
type Test struct {
    Name         string `bson:"name"`
    Age         int    `bson:"age"`
    CreateTime int64  `bson:"createTime"`
    UpdateTime int64  `bson:"updateTime"`

func initMongdb() error {
    //1. Establish mongodb connection
    //Fill in your mongdb address. The default port is 27017
    clientOptions := options.Client().ApplyURI("mongodb://admin:[email protected]:27017/admin?authMechanism=SCRAM-SHA-1")
    mclient, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        return err
    //2. Select database my_ db
    database := mclient.Database("admin")
    //3. Select table my_ collection
    collection := mgMongoDatabase.Collection("deviceToken")

    mlog.Info("connect mongdb successfully")

    //Insert data
    record := &Test{
        Name: "Little Devil boy",
        CreateTime: time.Now().Unix(),
        UpdateTime: time.Now().Unix(),
    result, err := collection.InsertOne(context.TODO(), record)
    if err != nil {
        return err
    //Update data
   // if err := UpdateData(bson.M{"name": "xxxx"}, bson.D{{"$set", bson.M{"age": 15}}}); err != nil {
    //        mlog.Error(err)
    //        return
    //    }

    //Query a single record
    //data := &DeviceToken{}
    //err = collection.FindOne(context.TODO(),bson.M{}).Decode(data)

    //Query all records
    data := []DeviceToken{}
    cursor, err := collection.Find(context.TODO(), bson.M{})
    cursor.All(context.TODO(), &data)
    //Delete a record
    //res ,err := mgMongoCollection.DeleteOne(context.TODO(),bson.M{"name":"xxxx"})
    //if err != nil{
    //    mlog.Warn(err)

    return nil

InterestedXDMYou can practice more and paste the above code into your own environment to see the effect. The above mainly describes the following operations:

  • connectmongodbdatabase
  • Select the corresponding library and table
  • Insert one piece of data / insert multiple pieces of data
  • Update one piece of data / insert multiple pieces of data
  • Query a new piece of data / insert multiple pieces of data
  • Delete a new piece of data / insert multiple pieces of data

The basic application of the corresponding database is still very simple, but after we will apply it, we must carefully taste the principles, how the official or third-party package is implemented, and whether we can write a version ourselves

Interested partners can try to go deeper


  • Introduction to mongodb
  • How to install mongodb
  • How to use mongodb simply
  • How does go operate mongodb

Welcome to like, follow and collect

My friends, writing is not easy

Your support and encouragement is my motivation to share and improve quality

Mongdb installation and use

Well, that’s all for this time

Technology is open, and our mentality should be open. Embrace change, live in the sun and strive to move forward.

I amLittle Devil boy Nezha, welcome to like and pay attention to the collection. See you next time~

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]