内容简介:本文基于第一个
本文基于 MongoDB
的 Node.JS
驱动实现 MongoDB
基本的增删改查操作。驱动官方文档见: mongodb.github.io/node-mongod…
。
1 插入文档
MongoDB
中 Collection
类的 insertOne
和 insertMany
方法用来插入文档。
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
中无需显示的创建集合 inserts
, MongoDB
服务会在首次插入文档时自动创建该集合。 insertOne
和 insertMany
方法接收第二个参数 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
类的 updateOne
和 updateMany
方法用于实现更新操作。
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);
}
})();
复制代码
updateOne
和 updateMany
方法接收第三个参数 options
,可以用来配置 写关注
、 更新并插入
等参数,具体参数列表见: mongodb.github.io/node-mongod…
。
3 删除文档
Collection
类的 deleteOne
和 deleteMany
方法可以用来删除文档。
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);
}
})();
复制代码
deleteOne
和 deleteMany
方法可以接收第二个参数 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);
}
})();
复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- mongoose的增删改查
- JDBC实现简单增删改查
- Golang操作MySQL增删改查
- iOS CoreData (一) 增删改查
- CMDB_基础模型(增删改查)
- Mybatis增删改查之Oracle
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
算法艺术与信息学竞赛
刘汝佳 / 清华大学出版社 / 2004-1 / 45.00元
《算法艺术与信息学竞赛》较为系统和全面地介绍了算法学最基本的知识。这些知识和技巧既是高等院校“算法与数据结构”课程的主要内容,也是国际青少年信息学奥林匹克(IOI)竞赛和ACM/ICPC国际大学生程序设计竞赛中所需要的。书中分析了相当数量的问题。 本书共3章。第1章介绍算法与数据结构;第2章介绍数学知识和方法;第3章介绍计算机几何。全书内容丰富,分析透彻,启发性强,既适合读者自学,也适合于课......一起来看看 《算法艺术与信息学竞赛》 这本书的介绍吧!