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

系统管理员 2022-03-16 07:38 323阅读 0赞

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

1 插入文档

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

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URl
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function() {
  9. try {
  10. await client.connect();
  11. console.log('connected correctly to server');
  12. const db = client.db(dbName);
  13. // Insert a single document
  14. let r = await db.collection('inserts').insertOne({
  15. a: 1});
  16. assert.equal(1, r.insertedCount);
  17. // Insert multiple documents
  18. r = await db.collection('inserts').insertMany([{
  19. a: 2}, {
  20. a: 3}]);
  21. assert.equal(2, r.insertedCount);
  22. // Close connection
  23. client.close();
  24. } catch(err) {
  25. console.log(err.stack);
  26. }
  27. })();
  28. 复制代码

第一个insert语句向inserts集合中插入单个文档,注意在MongoDB中无需显示的创建集合insertsMongoDB服务会在首次插入文档时自动创建该集合。 insertOneinsertMany方法接收第二个参数options,可以配置写关注函数序列化等参数,具体参数列表见:mongodb.github.io/node-mongod…。 例如下面这段代码会将传入的函数序列化并写入到副本集replica set

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function() {
  9. try {
  10. await client.connect();
  11. console.log('connected correctly to server');
  12. const db = client.db(dbName);
  13. // Insert a single document
  14. const r = await db.collection('inserts').insertOne({
  15. a: 1,
  16. b: function () {
  17. return 'hello';}
  18. }, {
  19. w: 'majority',
  20. wtimeout: 10000,
  21. serializeFunctions: true,
  22. forceServerObjectId: true
  23. });
  24. assert.equal(1, r.insertedCount);
  25. client.close();
  26. } catch(err) {
  27. console.log(err.stack);
  28. }
  29. })();
  30. 复制代码

2 更新文档

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

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. // Get the updates collection
  14. const col = db.collection('updates');
  15. // Insert some documents
  16. let r = await col.insertMany([{
  17. a: 1}, {
  18. a: 2}, {
  19. a: 2}]);
  20. assert.equal(3, r.insertedCount);
  21. // Update a single document
  22. r = await col.updateOne({
  23. a: 1}, {
  24. $set: {
  25. b: 1}});
  26. assert.equal(1, r.matchedCount);
  27. assert.equal(1, r.modifiedCount);
  28. // Update multiple documents
  29. r = await col.updateMany({
  30. a: 2}, {
  31. $set: {
  32. b: 2}});
  33. assert.equal(2, r.matchedCount);
  34. assert.equal(2, r.modifiedCount);
  35. // Upsert a single document
  36. r = await col.updateOne({
  37. a: 3}, {
  38. $set: {
  39. b: 3}});
  40. assert.equal(0, r.matchedCount);
  41. assert.equal(1, r.upsertedCount);
  42. // Close connection
  43. client.close();
  44. } catch(err) {
  45. console.log(err.stack);
  46. }
  47. })();
  48. 复制代码

updateOneupdateMany方法接收第三个参数options,可以用来配置写关注更新并插入等参数,具体参数列表见:mongodb.github.io/node-mongod…。

3 删除文档

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

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. // Get the collection to remove
  14. const col = db.collection('removes');
  15. // Insert some documents
  16. let r = await col.insertMany([{
  17. a: 1}, {
  18. a: 2}, {
  19. a: 2}]);
  20. assert.equal(3, r.insertedCount);
  21. // Remove a single document
  22. r = await col.deleteOne({
  23. a: 1});
  24. assert.equal(1, r.deletedCount);
  25. // Remove multiple documents
  26. r = await col.deleteMany({
  27. a: 2});
  28. assert.equal(2, r.deletedCount);
  29. // Close connection
  30. client.close();
  31. } catch(err) {
  32. console.log(err.stack);
  33. }
  34. })();
  35. 复制代码

deleteOnedeleteMany方法可以接收第二个参数options,用来配置写关注等参数,具体参数列表见:mongodb.github.io/node-mongod…。

4 查询文档

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

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. // Get the collection
  14. const col = db.collection('find');
  15. // Insert some documents
  16. const r = await col.insertMany([{
  17. a: 1}, {
  18. a: 1}, {
  19. a: 1}]);
  20. assert.equal(3, r.insertedCount);
  21. // Get first two documents that match the query
  22. const docs = await col.find({
  23. a: 1}).limit(2).toArray();
  24. assert.equal(2, docs.length);
  25. // Close connection
  26. client.close();
  27. } catch(err) {
  28. console.log(err.stack);
  29. }
  30. })();
  31. 复制代码

方法find返回的游标支持各种链式调用,具体支持的方法见:mongodb.github.io/node-mongod…。 例如下面的代码使用游标next方法进行迭代:

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. // Get the collection
  14. const col = db.collection('find');
  15. // Insert some documents
  16. const r = col.insertMany([{
  17. a: 1}, {
  18. a: 1}, {
  19. a: 1}]);
  20. assert.equal(3, r.insertedCount);
  21. // Get the cursor
  22. const cursor = col.find({
  23. a: 1}).limit(2);
  24. // Iterate over the cursor
  25. while(await cursor.hasNext()) {
  26. const doc = cursor.next();
  27. console.dir(doc);
  28. }
  29. // Close connection
  30. client.close();
  31. } catch(err) {
  32. console.log(err.stack);
  33. }
  34. })();
  35. 复制代码

下面的代码使用游标each方法进行迭代:

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database Name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. const col = db.collection('find');
  14. const r = await col.insertMany([{
  15. a:1}, {
  16. a:1}, {
  17. a:1}]);
  18. assert.equal(3, r.insertedCount);
  19. col.find({
  20. a: 1}).limit(2).each((err, doc) => {
  21. if (doc) {
  22. console.dir(doc);
  23. } else {
  24. client.close();
  25. return false;
  26. }
  27. });
  28. } catch(err) {
  29. console.log(err.stack);
  30. }
  31. })();
  32. 复制代码

5 投影

默认情况下,查询会返回文档的所有字段,可以通过投影(projection)来限制MongoDB服务返回的字段。投影配置文档用来控制返回包含哪些字段、不包含哪些字段:

  1. { field1: <value>, field2: <value> ... }
  2. 复制代码

<value>0false表示不包含,1true表示包含。_id字段默认返回,无需配置。除了_id字段外,其他所有字段的配置不可以同时出现01。下面的例子仅返回age字段:

  1. const MongoClient = require('mongodb').MongoClient;
  2. const assert = require('assert');
  3. // Connection URL
  4. const url = 'mongodb://localhost:27017';
  5. // Database Name
  6. const dbName = 'myproject';
  7. const client = new MongoClient(url);
  8. (async function () {
  9. try {
  10. await client.connect();
  11. console.log("Connected correctly to server");
  12. const db = client.db(dbName);
  13. const col = db.collection('project');
  14. let r = await col.insertMany([{
  15. name: 'Jim', age: 18}, {
  16. name: 'Lucy', age: 16}]);
  17. assert.equal(2, r.insertedCount);
  18. r = await col.find({
  19. name: 'Jim'}).project({
  20. age: 1, _id: 0}).toArray();
  21. console.log(r);
  22. // Close connection
  23. client.close();
  24. } catch (err) {
  25. console.log(err.stack);
  26. }
  27. })();
  28. 复制代码

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读