MongoDB基本增刪改查操做-基於Node.JS驅動

本文基於MongoDBNode.JS驅動實現MongoDB基本的增刪改查操做。驅動官方文檔見:mongodb.github.io/node-mongod…javascript

1 插入文檔

MongoDBCollection類的insertOneinsertMany方法用來插入文檔。html

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);
    }
})();
複製代碼

第一個insert語句向inserts集合中插入單個文檔,注意在MongoDB中無需顯示的建立集合insertsMongoDB服務會在首次插入文檔時自動建立該集合。 insertOneinsertMany方法接收第二個參數options,能夠配置寫關注函數序列化等參數,具體參數列表見:mongodb.github.io/node-mongod…。 例以下面這段代碼會將傳入的函數序列化並寫入到副本集replica setjava

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);
    }
})();
複製代碼

2 更新文檔

Collection類的updateOneupdateMany方法用於實現更新操做。node

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);
    }
})();
複製代碼

updateOneupdateMany方法接收第三個參數options,能夠用來配置寫關注更新並插入等參數,具體參數列表見:mongodb.github.io/node-mongod…git

3 刪除文檔

Collection類的deleteOnedeleteMany方法能夠用來刪除文檔。github

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);
    }
})();
複製代碼

deleteOnedeleteMany方法能夠接收第二個參數options,用來配置寫關注等參數,具體參數列表見:mongodb.github.io/node-mongod…mongodb

4 查詢文檔

查詢MongoDB的主要方法是find方法。find方法返回一個用來操做數據的遊標。下面的代碼限制查詢個數爲2條文檔,並使用toArray方法導出文檔。api

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);
    }
})();
複製代碼

方法find返回的遊標支持各類鏈式調用,具體支持的方法見:mongodb.github.io/node-mongod…。 例以下面的代碼使用遊標next方法進行迭代:async

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);
    }
})();
複製代碼

下面的代碼使用遊標each方法進行迭代:函數

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);
    }
})();
複製代碼

5 投影

默認狀況下,查詢會返回文檔的全部字段,能夠經過投影(projection)來限制MongoDB服務返回的字段。投影配置文檔用來控制返回包含哪些字段、不包含哪些字段:

{ field1: <value>, field2: <value> ... }
複製代碼

<value>0false表示不包含,1true表示包含。_id字段默認返回,無需配置。除了_id字段外,其餘全部字段的配置不能夠同時出現01。下面的例子僅返回age字段:

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);
    }
})();
複製代碼
相關文章
相關標籤/搜索