In this paper, the node. JS driver of MongoDB is used to implement the basic add, delete, change and check operations of MongoDB. Github. IO /node-mongod… .

1 Inserting a Document

The insertOne and insertMany methods of the Collection class in MongoDB are used to insert documents.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URl
const url = 'mongodb://localhost:27017';

// Database name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function() {
    try {
        await client.connect();
        console.log('connected correctly to server');
        const db = client.db(dbName);
        
        // Insert a single document
        let r = await db.collection('inserts').insertOne({a: 1});
        assert.equal(1, r.insertedCount);
        
        // Insert multiple documents
        r = await db.collection('inserts').insertMany([{a: 2}, {a: 3}]);
        assert.equal(2, r.insertedCount);
        
        // Close connection
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

The first INSERT statement inserts a single document into a Inserts collection. Note that the create collection inserts that do not need to be displayed in MongoDB are automatically created by the MongoDB service when the document is first inserted. The insertOne and insertMany methods receive the second parameter options, which can be set to write attention, function serialization, etc. See mongodb.github. IO /node-mongod… . For example, the following code serializes the passed function and writes it to the replica set:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'myproject';

const client = new MongoClient(url);
(async function() {
    try {
        await client.connect();
        console.log('connected correctly to server');
        const db = client.db(dbName);
        
        // Insert a single document
        const r = await db.collection('inserts').insertOne({
            a: 1.b: function () {return 'hello';} 
        }, {
            w: 'majority'.wtimeout: 10000.serializeFunctions: true.forceServerObjectId: true
        });
        
        assert.equal(1, r.insertedCount);
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

2 Updating documents

The updateOne and updateMany methods of the Collection class are used to implement the update operation.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);

        // Get the updates collection
        const col = db.collection('updates');
        // Insert some documents
        let r = await col.insertMany([{a: 1}, {a: 2}, {a: 2}]);
        assert.equal(3, r.insertedCount);
        
        // Update a single document
        r = await col.updateOne({a: 1}, {$set: {b: 1}});
        assert.equal(1, r.matchedCount);
        assert.equal(1, r.modifiedCount);
        
        // Update multiple documents
        r = await col.updateMany({a: 2}, {$set: {b: 2}});
        assert.equal(2, r.matchedCount);
        assert.equal(2, r.modifiedCount);
        
        // Upsert a single document
        r = await col.updateOne({a: 3}, {$set: {b: 3}});
        assert.equal(0, r.matchedCount);
        assert.equal(1, r.upsertedCount);
        
        // Close connection
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

The updateOne and updateMany methods receive the third parameter options, which can be used to configure write attention, update, and insert parameters. For details, see mongodb.github. .

3 Deleting a Document

The deleteOne and deleteMany methods of the Collection class can be used to delete documents.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);

        // Get the collection to remove
        const col = db.collection('removes');
        // Insert some documents
        let r = await col.insertMany([{a: 1}, {a: 2}, {a: 2}]);
        assert.equal(3, r.insertedCount);

        // Remove a single document
        r = await col.deleteOne({a: 1});
        assert.equal(1, r.deletedCount);

        // Remove multiple documents
        r = await col.deleteMany({a: 2});
        assert.equal(2, r.deletedCount);

        // Close connection
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

The deleteOne and deleteMany methods receive a second parameter, options, which is used to configure parameters such as write concerns. For details, see mongodb.github. .

4 Querying Documents

The primary method of querying MongoDB is the find method. The find method returns a cursor that manipulates data. The following code limits the number of queries to two documents and exports the documents using the toArray method.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);
        
        // Get the collection
        const col = db.collection('find');
        // Insert some documents
        const r = await col.insertMany([{a: 1}, {a: 1}, {a: 1}]);
        assert.equal(3, r.insertedCount);
        
        // Get first two documents that match the query
        const docs = await col.find({a: 1}).limit(2).toArray();
        assert.equal(2, docs.length);
        
        // Close connection
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

The find method returns a cursor that supports a variety of chained calls. See mongodb.github. IO /node-mongod… . For example, the following code iterates using the next method of the cursor:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);
        
        // Get the collection
        const col = db.collection('find');
        // Insert some documents
        const r = col.insertMany([{a: 1}, {a: 1}, {a: 1}]);
        assert.equal(3, r.insertedCount);
        
        // Get the cursor
        const cursor = col.find({a: 1}).limit(2);
        
        // Iterate over the cursor
        while(await cursor.hasNext()) {
            const doc = cursor.next();
            console.dir(doc);
        }
        
        // Close connection
        client.close();
    } catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

The following code iterates using the each method of the cursor:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);
        
        const col = db.collection('find');
        const r = await col.insertMany([{a:1}, {a:1}, {a:1}]);
        assert.equal(3, r.insertedCount);
        col.find({a: 1}).limit(2).each((err, doc) = > {
            if (doc) {
                console.dir(doc);
            } else {
                client.close();
                return false; }}); }catch(err) {
        console.log(err.stack);
    }
})();
Copy the code

5 the projection

By default, queries return all the fields of the document, and projections can be used to limit the fields returned by the MongoDB service. The projection configuration document is used to control which fields are included and not included in the return:

{ field1: <value>, field2: <value> ... }
Copy the code


0 or false indicates no inclusion, and 1 or true indicates inclusion. The _ID field is returned by default and no configuration is required. Except the _ID field, all other fields cannot contain 0 and 1 at the same time. The following example returns only the age field:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

const client = new MongoClient(url);

(async function () {
    try {
        await client.connect();
        console.log("Connected correctly to server");
        const db = client.db(dbName);

        const col = db.collection('project');
        let r = await col.insertMany([{name: 'Jim'.age: 18}, {name: 'Lucy'.age: 16}]);
        assert.equal(2, r.insertedCount);
        
        r = await col.find({name: 'Jim'}).project({age: 1._id: 0}).toArray();
        console.log(r);

        // Close connection
        client.close();
    } catch (err) {
        console.log(err.stack);
    }
})();
Copy the code