阅读 203

MongoDB基本增删改查操作-基于Node.JS驱动

本文基于MongoDBNode.JS驱动实现MongoDB基本的增删改查操作。驱动官方文档见:mongodb.github.io/node-mongod…

1 插入文档

MongoDBCollection类的insertOneinsertMany方法用来插入文档。

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 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);
    }
})();
复制代码

2 更新文档

Collection类的updateOneupdateMany方法用于实现更新操作。

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…

3 删除文档

Collection类的deleteOnedeleteMany方法可以用来删除文档。

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…

4 查询文档

查询MongoDB的主要方法是find方法。find方法返回一个用来操作数据的游标。下面的代码限制查询个数为2条文档,并使用toArray方法导出文档。

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方法进行迭代:

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);
    }
})();
复制代码
关注下面的标签,发现更多相似文章
评论