I. Introduction to Mongodb

MongodbIs a document database that stores data as documents in a similar formatJSON

Compare with the characteristics and selection of Mysql

Mongodb Mysql
Relationship types non-relational relational
Storage type Document storage (similar to writing Word) Table storage (similar to writing Excle)
Operation type NoSQL operations (no NEED to write SQL statements) SQL operations
Selection of reference Suitable for storage format comparisonlooseInformation such as “crawler” down the data Suitable for storage format comparisonneatThe information of

Note: This is not to say that you have to choose between two databases in a real project; you can use both. For regular information such as user information table, Mysql database can be used to store it, but for large sections of rich text information such as blog content in web pages (including text, video, pictures, etc.), it is not appropriate to store it in a field of Mysql database, so this blog content can be stored by Mongodb.

Second, Mongodb and Compass installation

Online installation of a lot of information, I will not repeat here, we can be installed according to the following reference blog

Mongo installation

Windows platform installation link

Mac OS platform Installation link (Brew is recommended)

After I install the default running Mongodb server, and connect to the Mongodb, you can operate directly through the command line. If you cannot connect to Mongodb, refer to the setup connection configuration above.

Directing a Compass installed

Mongodb Compass is an official recommended visualization tool for easy and intuitive data browsing and manipulation

The install link

3. Important Concepts

1. Mysql

For relational databases, the use is usually to create a database first, and then create a table, and then add, delete, change and check records

However, there are some differences between these terms in Mongodb. The steps are as follows:

  • Create a database (database), andMysqlThe same
  • Create a collection (collection), the correspondingMysqlIn the table
  • The document (document) add, delete, change, check — correspondingMysqlIn the record of the increase, deletion, change and check

2, BSON

  • MongodbThe format used for the document isBSON
  • BSON = Binary JSONIs of binary typeJSON

4. Use Compass to run Mongodb

1. The interface after opening is as shown in the figure. Click “CONNECT” to CONNECT

2. The newly installed Mongodb has three databases by default. Click “CREATE DATABASE” to CREATE the DATABASE

Create databases and collections

4. Click “ADD DATA” to ADD documents

5. The document format is as follows:

6. Search, modify and delete documents

Note: The data entered during lookup is also in a JSON-like format

5. Use the command line to operate Mongodb

Open bin/mongo.exe in the Mongodb directory

Note: Please change dbName and collName to the name of the database or collection created by yourself

1. View operations

#See what databases are available
show dbs

#Create or enter a database (created when the database does not exist)
use dbName

#See what collections are available
show collections
Copy the code

Create a collection/insert a document into the collection

#You can insert data directly into collections, and pairs of collections that do not exist will be created
db.collName.insert({"name":"Axton", "age":20}) 
Copy the code

3. Display documents in the collection

#Displays all documents in the collection
db.collName.find()

#Displays specific documents in the collection
db.collName.find({ "name":"Axton" })

#Sort by ID in reverse order
db.collName.find().sort({_id:-1})
Copy the code

4. Update documentation

db.collName.update({"name":"Axton", $set:{"name": "Axton2"}})
Copy the code

5. Delete the document

db.collName.remove({"name": "Axton"})
Copy the code

Node.js uses the mongodb plug-in to connect to the database

1. Initialize the environment

#Initialize the Node.js environment
npm init -y

#Installing the mongodb module
npm i mongodb --save
Copy the code

2. Connect to Mongodb

const MongoClient = require('mongodb').MongoClient

const url = 'mongodb://localhost:27017'		// The default port number is 27017. If you have changed it, change it by yourself
const dbName = 'mydb'		// The name of the database to connect to

MongoClient.connect(
  url,
  {
    // Configure (by default, write it)
    useUnifiedTopology: true
  },
  (err, client) = > {
    if (err) {
      console.error('mongodn connect error', err)
      return
    }

    console.log('mongodb connect success')

    // Switch to the database
    const db = client.db(dbName)

    // Close the connection
    client.close()
  }
)
Copy the code

3. Operation of Document

Query the document

const MongoClient = require('mongodb').MongoClient

const url = 'mongodb://localhost:27017'
const dbName = 'mydb'

MongoClient.connect(
  url, 
  {
    useUnifiedTopology: true
  },
  (err, client) = > {
    if (err) {
      console.error('mongodn connect error', err)
      return
    }
    console.log('mongodb connect success')
    const db = client.db(dbName)

    // Use collections
    const usersCollection = db.collection('students')

    // the operation code of the ------- document is written in this section, after which the connection part of the code ------- will not be included
    // Query the document
    usersCollection.find({	// find() does not write content to query the entire document
        "name" : "Axton"
    }).toArray((err, res) = > {
      if (err) {
        console.error(err)
        return
      }
      console.log(res)

      // find() is an asynchronous operation, so that the data is closed after the query
      client.close()
    })
    // -------------------------------------------------------------})Copy the code

Inserted into the document

InsertMany () insertMany()
usersCollection.insertOne({
  name: 'Jack'.sex: 'male'.age: 21
}, (err, res) = > {
  if (err) {
    console.error(err)
    return
  }
  console.log(res)
  client.close()
})
Copy the code

Update the document

UpdateMany ()
usersCollection.updateOne(
  {name: 'Jack'},   // Query conditions
  {$set: {info: 'ladies'}},   // The updated content
   (err, res) = > {
     if (err) {
       console.error(err)
       return
     }
     console.log(res)
     client.close()
  }
)
Copy the code

Delete the document

DeleteMany () = deleteMany();
usersCollection.deleteOne({
    name: 'Jack'
}, (err, res) = > {
    if (err) {
        console.error(err)
        return
    }
    console.log(res)
    client.close()
})
Copy the code

4, description,

Mongodb is a low-level plug-in, learn to use this plug-in is to let you understand some of the principles of connecting to mongodb. On a daily basis, the Mongoose plugin is used to facilitate project development

7. Use mongoose plug-in to connect database in Node.js

1, description,

Because the data format of mongodb is too flexible, it is easy to lead to errors in data format during multi-party development. Therefore, mongoose can be used in a more standardized way.

Important nouns and operations

  • Schema Specifies the data format specification
  • Specification Collection in Model
  • An API to regulate data manipulation

2. Initialize the environment

Install the Mongoose plug-in

npm i mongoose --save
Copy the code

The directory structure

Mongoose - test ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ node_modules └ ─ ─ the SRC ├ ─ ─ the js ├ ─ ─ models │ └ ─ ─ Student. Js └ ─ ─ The test └ ─ ─ student. JsCopy the code

3. Create a connection service

db.js

const mongoose = require('mongoose')

const url = 'mongodb://localhost:27017'
const dbName = 'myblog'

mongoose.connect(`${url}/${dbName}`, {
  useUnifiedTopology: true.useNewUrlParser: true
})

const db = mongoose.connection    // Assign the connection object to db

// Error sending
db.on('error'.err= > {
  console.error(err)
})

// The connection succeeded
db.on('open'.() = > {
  console.log('success! ')})module.exports = mongoose
Copy the code

Define the Schema specification and create the model

models/Students.js

// Corresponds to the students set

const mongoose = require('.. /db')

// Use Schema to define data specifications
const StudentSchema = mongoose.Schema({
  name: {
    type: String.required: true.unique: true
  },
  sex: String.age: Number
}, {
  timestamps: true  // The timestamp will be added to the corresponding time data after inserting and updating data
  // Add createdAt and updatedAt to each document
})

// Model for Collection
const Student = mongoose.model('student', StudentSchema)

module.exports = Student
Copy the code

5. Operation of Document

test/students.js

Query the document

const Student = require('.. /models/Student')

// self-executing asynchronous function! (async() = > {// Query the document
  const res = await Student.find({
    name: 'Axton'
  })

  // Fuzzy query documents with regular expressions
  const res2 = await Student.find({
    name: /A/
  })
  
  // Query a single document by ID
  const res3 = await Student.findById('5fb2247e6469170600f02551')

})()
Copy the code

Inserted into the document

const Student = require('.. /models/Student')

!(async() = > {// Insert the document
  const res = await Student.create({
    name: 'Jack'.age: 21.sex: 'male'
  })

})()
Copy the code

Update the document

const Student = require('.. /models/Student')

!(async() = > {// Update the document
  const res = await Student.findOneAndUpdate(
    {name: 'Jack'},   // Query conditions
    {sex: 'woman'},
    {
      new: true  // Return the modified content, default is fasle})}) ()Copy the code

Delete the document

const Student = require('.. /models/Student')

!(async() = > {// Delete the document
  const res = await Student.findOneAndDelete({
    name: 'Jack'
  })

})()
Copy the code

Eight, write at the end of the article

In this paper, the basic operations such as connecting mongodb and Node.js to mongodb are sorted out and summarized, which can be used in some common scenarios. You can refer to the official documentation for more advanced operations. If you find anything wrong or poorly written in this article, please point it out in the comments section.