[Buddhist notes] - operate mongodb with node

Posted by xenophobia on Tue, 05 Nov 2019 08:13:59 +0100

  • The notes series of the Buddhism department is a rough summary, which does not seek to be profound but can only be used.

Using node to operate mongodb

First of all, I assume that mongodb has been installed in your computer. Now let's see how to use nodeJS to operate mongodb. The simple database can also be used for the front-end Xiaobai of services built with nodeJS.

1. Create a new project and install mongodb

Create a new project and install mongodb in the project

cnpm install mongodb
// or
npm install mongodb
// or
yarn add mongodb

2. Connect to database

Suppose everyone's node entry is index.js. For each operation of the database, you must follow:

  1. Connect to database
  2. Operation database
  3. Close database (disconnect)

First, we use mongodb module to create a connection. A successful console output connection means that the operation is correct.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
  if (err) throw err;
  console.log("Successful connection");
  db.close();  // close database
});

3. Operation database

The structure of mongodb database is database collection data.

1. Create database

Let's start with creating a database. mongodb is different from mysql in that it will be generated automatically when the accessed database does not exist.

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    // db is the database instance after successful connection
    if (err) throw err;
    // Use dB (database name) to operate the database, otherwise create
    var dbo = db.db("testDB");
        console.log("Create database testDB Success");
        db.close();
});

2. Create a collection

Create a collection with the createCollection() method of the database instance. The first parameter of createCollection is the collection name, and the second parameter is a function, which returns the operation information.

MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
    if (err) throw err;
    console.log('Database created');
    var dbase = db.db("testDB");
    // After getting the database instance with DB (database name), create the collection with createCollection
    dbase.createCollection('site', function (err, res) {
        if (err) throw err;
        console.log("Create set!");
        db.close();
    });
});

3. Delete set

Use the drop() method to delete the collection:

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    // Delete test set
    dbo.collection("test").drop(function(err, delOK) {  // If the execution succeeds, delOK returns true, otherwise false
        if (err) throw err;
        if (delOK) console.log("Collection deleted");
        db.close();
    });
});

4. Insert data

Access the collection with collection() and insert the data with insertOne. To insert multiple pieces of information, you can use insertMany():

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var myobj = { name: "Rookie tutorial", url: "www.testDB" };
    dbo.collection("site").insertOne(myobj, function(err, res) {
        // The second parameter is a function that returns the operation information
        if (err) throw err;
        console.log("Document inserted successfully");
        db.close();
    });
});
// To insert multiple pieces of information, you can use insertMany():
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var myobj =  [
        { name: 'Rookie tools', url: 'https://c.testDB.com', type: 'cn'},
        { name: 'Google', url: 'https://www.google.com', type: 'en'},
        { name: 'Facebook', url: 'https://www.google.com', type: 'en'}
       ];
    dbo.collection("site").insertMany(myobj, function(err, res) {
        if (err) throw err;
        console.log("The number of documents inserted is: " + res.insertedCount);
        db.close();
    });
});

5. Query data

Using find to query data on an instance of a collection

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
     var whereStr = {"name":'Zhang San'};  // query criteria
    dbo.collection("site").find(whereStr).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
});


// If you want to query all data, you don't need to transfer conditions
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    dbo.collection("site"). find({}).toArray(function(err, result) { // Return all data in the collection
        if (err) throw err;
        console.log(result);
        db.close();
    });
});

6. Update (modify) data

The collection instance uses updateOne to modify data. The following instance changes the age with name "Zhang San" to 23:

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var whereStr = {"name":'Zhang San'};  // query criteria
    var updateStr = {$set: { "age" : "23" }};
    dbo.collection("site").updateOne(whereStr, updateStr, function(err, res) {
        if (err) throw err;
        console.log("Document updated successfully");
        db.close();
    });
});


// Similarly, if you want to modify multiple pieces of data, use updateMany();
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var whereStr = {"type":'en'};  // query criteria
    var updateStr = {$set: { "url" : "https://www.testDB.com" }};
    dbo.collection("site").updateMany(whereStr, updateStr, function(err, res) {
        if (err) throw err;
         console.log(res.result.nModified + " Documents updated");
        db.close();
    });
});

7. Delete data

As with updating, many data modifications, if you want to operate accurately, must first find the corresponding data through find

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var whereStr = {"name":'Zhang San'};  // query criteria
    dbo.collection("site").deleteOne(whereStr, function(err, obj) {
        if (err) throw err;
        console.log("Document deleted successfully");
        db.close();
    });
});

// If you want to delete multiple statements, you can use the deleteMany() method

8. ranking

Use the sort() method, which takes a parameter that specifies whether it is ascending (1) or descending (- 1).

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    var mysort = { type: 1 };
    dbo.collection("site").find().sort(mysort).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
});

9. paging

Use limit to filter several pieces of data, and skip to select several pieces of data

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    dbo.collection("site").find().limit(2).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
  });
});

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testDB");
    dbo.collection("site").find().skip(2).limit(2).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
  });
});

Reference article address

Topics: node.js Database MongoDB Google npm