introduce

MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.

MongoDB is a product between relational database and non-relational database. Among non-relational databases, it has the most rich functions and is the most like relational database.

The installation

MongoDB installation and configuration tutorials

Basic use of MongoDB

Download the dependent

cnpm i mongodb -S

The basic use

/ / introduction
const MongoClient = require('mongodb').MongoClient;

(async function () {
    / / for the client
    const client = new MongoClient('mongodb://localhost:27017', {
        useNewUrlParser: true /* Parses */ with the new URL parser
    });
    // Connect to the server
    await client.connect();
    console.log('Connection successful');
    // Get the database
    const db = client.db('luffycity');
    // Get the collection
    const grades = db.collection('grades');
    // Delete all data first
    grades.deleteMany();
    // Insert a piece of data using insertOne()
    grades.insertOne({
        name: 'holo'.age: 20.hobby: ['eat'.'sleep'.'Beat the beans'].score: 86
    });
    // Close the connectionclient.close(); }) ()Copy the code

Insert multiple numbers using insertMany()

    // Insert more data
    // Return a promise
    let res = await grades.insertMany([{
        name: 'tom'.age: 18.hobby: ['Catch a mouse'.'sleep'.'Beat the beans'].score: 91
    }, {
        name: 'jerry'.age: 17.hobby: ['to make the cat'.'sleep'.'Beat the beans'].score: 88
    }])
    console.log('Inserted successfully', res);
Copy the code

Returns the res

Res.result. ok is used to determine whether the insert is successful. Res.result. n is the number of inserts.

    // Return the res
    {
  	result: { ok: 1.n: 2 },
  	ops: [{name: 'tom'.age: 18.hobby: [Array].score: 91._id: 5facdcf9cfceac3590ec63a5
          },
          {
            name: 'jerry'.age: 17.hobby: [Array].score: 88._id: 5facdcf9cfceac3590ec63a6
          }
  	],
  	insertedCount: 2.insertedIds: { '0': 5facdcf9cfceac3590ec63a5, '1': 5facdcf9cfceac3590ec63a6 }
    }
Copy the code

The query

Example Query a single piece of data

    let res = await grades.findOne({
        name: 'jerry'
    });
    console.log(res);
Copy the code

Querying multiple pieces of Data

Tips: The returned result needs to be converted to the desired format by toArray().

    ToArray () to convert multiple queries to the desired format
    let res = await grades.find().toArray();
    console.log(res);
Copy the code

Specify search criteria

    let res = await grades.find({
        name: 'tom'
    }).toArray();
Copy the code

Comparison operator$gt

    let res = await grades.find({
        age: {
            $gt: 18 // Get age > 18
        }
    }).toArray();
    console.log(res);
Copy the code

Logical operator$and

    // $and
    // Get the name 'holo' and age 26
    let res = await grades.find({
        name: 'holo'.age: 26
    }).toArray();
    console.log(res);
Copy the code

Regular expression

    let res = await grades.find({
        name: {
            // The name begins with H
            $regex: /^h/
        }
    }).toArray();
    console.log(res);
Copy the code

$all,$in,$size

  • $all: Finds all data containing the specified content in the specified field
    let res = await grades.find({
        hobby: {
            $all: ['Beat the beans']
        }
    }).toArray();
    console.log(res);
Copy the code
  • $in: Finds all data in a specified field that contains one of the specified contents
    let res = await grades.find({
        hobby: {
            $in: ['Beat the beans'.'Catch a mouse']
        }
    }).toArray();
    console.log(res);
Copy the code
  • $size: Finds all data in the specified field whose content length is size
    let res = await grades.find({
        hobby: {
            $size: 2
        }
    }).toArray();
    console.log(res);
Copy the code

More operators

More operators

Paging query

limit()

Query the first two data

    let res = await grades.find().limit(2).toArray();
    console.log(res);
Copy the code

skip()

Skip the first data and get the next two

    let res = await grades.find().skip(1).limit(2).toArray();
    console.log(res);
Copy the code

sort()

Sort by a field

    // An age value of 1 indicates positive order, and an age value of -1 indicates reverse order
    let res = await grades.find().sort({
        age: 1
    }).toArray();
    console.log(res);
Copy the code

paging

    const pageIndex = 2; // Current index
    const pageSize = 3; // The number of data displayed on each page
    let res = await grades.find().skip((pageIndex - 1) * pageSize).limit(pageSize).toArray();
    console.log(res);
Copy the code

Update the document

    // Change the name of holo and age 26 to 'booboo'
    let res = await grades.updateOne({
        name: 'holo'.age: 26
    }, {
        $set: {
            name: 'booboo'}})console.log(res.result);
Copy the code

Delete the document

    // Delete the data named jhon
    let res = await grades.deleteOne({
        name: 'jhon'
    })
    console.log(res.result);
Copy the code

Aggregation function

Tips: You need to group documents using $group before you can use aggregate functions

    let res = await grades.aggregate([{
        $group: {
            _id: '$age'.count: {
                $sum: 1
            }
        }
    }]).toArray();
    console.log(res);
Copy the code

_id: ‘$age’ = ‘age’; $sum: 1 =’ age’; $sum: 1 = ‘age’; $age =’ age’