原文: http://zetcode.com/javascript/mongodb/

MongoDB JavaScript 教程展示了如何在 JavaScript 中创建与 MongoDB 一起使用的程序。 本教程使用本地 mongodb 驱动程序。 (还有其他解决方案,例如 Mongoose 或 Monk。)

MongoDB

MongoDB 是 NoSQL 跨平台的面向文档的数据库。 它是可用的最受欢迎的数据库之一。 MongoDB 由 MongoDB Inc. 开发,并作为免费和开源软件发布。

MongoDB 中的记录是一个文档,它是由字段和值对组成的数据结构。 MongoDB 文档与 JSON 对象相似。 字段的值可以包括其他文档,数组和文档数组。 MongoDB 将文档存储在集合中。 集合类似于关系数据库中的表以及行中的文档。

安装 MongoDB 服务器

以下命令可用于在基于 Debian 的 Linux 上安装 MongoDB。

  1. $ sudo apt-get install mongodb

该命令将安装 MongoDB 随附的必要包。

  1. $ sudo service mongodb status
  2. mongodb start/running, process 975

使用sudo service mongodb status命令,我们检查mongodb服务器的状态。

  1. $ sudo service mongodb start
  2. mongodb start/running, process 6448

mongodb服务器由sudo service mongodb start命令启动。

MongoDB 驱动程序安装

我们设置了项目。

  1. $ node -v
  2. v11.5.0

我们使用 Node.js 版本 11.5.0。

  1. $ npm i mongodb

我们安装mongodb本机 JavaScript 驱动程序。 npm是 Node.js 包管理器。 MongoDB Node.js 驱动程序提供基于回调和基于Promise的交互。

MongoDB 创建数据库

mongo工具是 MongoDB 的交互式 JavaScript Shell 界面,它为系统管理员提供了一个界面,并为开发者提供了一种直接测试数据库查询和操作的方法。

  1. $ mongo testdb
  2. MongoDB shell version v4.0.7
  3. ...
  4. > db
  5. testdb
  6. > db.cars.insert({name: "Audi", price: 52642})
  7. > db.cars.insert({name: "Mercedes", price: 57127})
  8. > db.cars.insert({name: "Skoda", price: 9000})
  9. > db.cars.insert({name: "Volvo", price: 29000})
  10. > db.cars.insert({name: "Bentley", price: 350000})
  11. > db.cars.insert({name: "Citroen", price: 21000})
  12. > db.cars.insert({name: "Hummer", price: 41400})
  13. > db.cars.insert({name: "Volkswagen", price: 21600})

我们创建一个testdb数据库,并在cars集合中插入八个文档。

MongoDB Promise

Promise是用于延迟和异步计算的对象。 它表示尚未完成的操作,但有望在将来进行。

  1. asyncFunc()
  2. .then(value => { /* success */ })
  3. .catch(error => { /* failure */ })
  4. .finally( => { /* cleanup */};

then()方法始终返回Promise,这使我们能够链接方法调用。

注意:如果没有传递回调,MongoClientconnect将返回一个Promise

我们也可以使用async/await语法来处理Promise

MongoDB JS 驱动程序

在第一个示例中,我们打印 Node.js 驱动程序的版本。

driver_version.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. console.log(client.topology.clientInfo);
  7. client.close();
  8. });

在该示例中,我们连接到服务器并找到客户端信息。

  1. const mongo = require('mongodb');

我们使用mongodb模块。

  1. const client = mongo.MongoClient;

MongoClient用于连接到 MongoDB 服务器。

  1. const url = 'mongodb://localhost:27017';

这是数据库的 URL。 27017 是 MongoDB 服务器监听的默认端口。

  1. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {

使用connect()创建到数据库的连接。

  1. $ node driver_version.js
  2. { driver: { name: 'nodejs', version: '3.2.2' },
  3. os:
  4. { type: 'Windows_NT',
  5. name: 'win32',
  6. architecture: 'x64',
  7. version: '10.0.17134' },
  8. platform: 'Node.js v11.5.0, LE' }

驱动程序版本为 3.2.2。

MongoDB 列出数据库集合

listCollections()方法列出了数据库中的可用集合。

list_collections.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.listCollections().toArray().then((docs) => {
  8. console.log('Available collections:');
  9. docs.forEach((doc, idx, array) => { console.log(doc.name) });
  10. }).catch((err) => {
  11. console.log(err);
  12. }).finally(() => {
  13. client.close();
  14. });
  15. });

该示例连接到testdb数据库并检索其所有集合。

  1. db.listCollections().toArray().then((docs) => {
  2. console.log('Available collections:');
  3. docs.forEach((doc, idx, array) => { console.log(doc.name) });
  4. ...

listCollection()方法在testdb数据库中找到所有集合; 它们被打印到控制台。

注意:我们应该谨慎使用toArray()方法,因为它会导致大量的内存使用。

  1. }).catch((err) => {
  2. console.log(err);
  3. }).finally(() => {
  4. client.close();
  5. });

catch块中,我们捕获了任何潜在的异常,并在finally块中关闭了与数据库的连接。

注意:我们的应用是控制台程序; 因此,我们在程序结束时关闭连接。 在 Web 应用中,应重新使用连接。

  1. $ node list_collections.js
  2. Available collections:
  3. continents
  4. cars
  5. cities

在我们的数据库中,我们有这三个集合。

MongoDB 数据库统计

dbstats()方法获取数据库的统计信息。

dbstats.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.stats((err, stats) => {
  8. if (err) throw err;
  9. console.log(stats);
  10. client.close();
  11. })
  12. });

该示例连接到testdb数据库并显示其统计信息。

  1. $ node dbstats.js
  2. { db: 'testdb',
  3. collections: 3,
  4. views: 0,
  5. objects: 18,
  6. avgObjSize: 57.888888888888886,
  7. dataSize: 1042,
  8. storageSize: 69632,
  9. numExtents: 0,
  10. indexes: 3,
  11. indexSize: 69632,
  12. fsUsedSize: 136856346624,
  13. fsTotalSize: 254721126400,
  14. ok: 1 }

这是一个示例输出。

MongoDB 查找

find()函数为查询创建一个游标,该游标可用于遍历 MongoDB 的结果。

find_all.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.collection('cars').find({}).toArray().then((docs) => {
  8. console.log(docs);
  9. }).catch((err) => {
  10. console.log(err);
  11. }).finally(() => {
  12. client.close();
  13. });
  14. });

在示例中,我们从cars集合中检索所有文档。

  1. db.collection('cars').find({}).toArray().then((docs) => {

传递空查询将返回所有文档。

  1. $ node find_all.js
  2. [ { _id: 5cfcfc3438f62aaa09b52175, name: 'Audi', price: 52642 },
  3. { _id: 5cfcfc3a38f62aaa09b52176, name: 'Mercedes', price: 57127 },
  4. { _id: 5cfcfc3f38f62aaa09b52177, name: 'Skoda', price: 9000 },
  5. { _id: 5cfcfc4338f62aaa09b52178, name: 'Volvo', price: 29000 },
  6. { _id: 5cfcfc4838f62aaa09b52179, name: 'Bentley', price: 350000 },
  7. { _id: 5cfcfc4b38f62aaa09b5217a, name: 'Citroen', price: 21000 },
  8. { _id: 5cfcfc4f38f62aaa09b5217b, name: 'Hummer', price: 41400 },
  9. { _id: 5cfcfc5438f62aaa09b5217c,
  10. name: 'Volkswagen',
  11. price: 21600 } ]

这是输出。

MongoDB 计数文件

count()函数返回集合中匹配文档的数量。

count_documents.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.collection('cars').find({}).count().then((n) => {
  8. console.log(`There are ${n} documents`);
  9. }).catch((err) => {
  10. console.log(err);
  11. }).finally(() => {
  12. client.close();
  13. });
  14. });

该示例计算cars集合中的文档数。

  1. $ node count_documents.js
  2. There are 8 documents

现在,汽车集合中有八个文件。

MongoDB findOne

findOne()方法返回一个满足指定查询条件的文档。 如果多个文档满足查询条件,则此方法将根据反映磁盘上文档顺序的自然顺序返回第一个文档。

find_one.js

  1. const MongoClient = require('mongodb').MongoClient;
  2. const url = 'mongodb://localhost:27017';
  3. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  4. if (err) throw err;
  5. const db = client.db("testdb");
  6. let collection = db.collection('cars');
  7. let query = { name: 'Volkswagen' }
  8. collection.findOne(query).then(doc => {
  9. console.log(doc);
  10. }).catch((err) => {
  11. console.log(err);
  12. }).finally(() => {
  13. client.close();
  14. });
  15. });

该示例从cars集合中读取一个文档。

  1. let query = { name: 'Volkswagen' }

该查询包含汽车的名称-大众汽车。

  1. collection.findOne(query).then(doc => {

该查询将传递给findOne()方法。

  1. $ node find_one.js
  2. { _id: 8, name: 'Volkswagen', price: 21600 }

这是示例的输出。

MongoDB 异步/等待示例

使用async/await,我们可以轻松地以同步方式处理Promise

async_await.js

  1. const MongoClient = require('mongodb').MongoClient;
  2. const url = 'mongodb://localhost:27017';
  3. async function findCar() {
  4. const client = await MongoClient.connect(url, { useNewUrlParser: true })
  5. .catch(err => { console.log(err); });
  6. if (!client) {
  7. return;
  8. }
  9. try {
  10. const db = client.db("testdb");
  11. let collection = db.collection('cars');
  12. let query = { name: 'Volkswagen' }
  13. let res = await collection.findOne(query);
  14. console.log(res);
  15. } catch (err) {
  16. console.log(err);
  17. } finally {
  18. client.close();
  19. }
  20. }
  21. findCar();

该示例使用async/await读取一个文档。

  1. async function findCar() {

该函数具有async关键字。

  1. let res = await collection.findOne(query);

使用await,我们等待findOne()函数的结果。

MongoDB 查询运算符

可以使用 MongoDB 查询运算符(例如$gt$lt$ne)过滤数据。

read_gt.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let query = { price: { $gt: 30000 } };
  8. db.collection('cars').find(query).toArray().then((docs) => {
  9. console.log(docs);
  10. }).catch((err) => {
  11. console.log(err);
  12. }).finally(() => {
  13. client.close();
  14. });
  15. });

该示例打印汽车价格大于 30,000 的所有文档。

  1. let query = { price: { $gts: 30000 } };

$gt运算符用于获取价格大于 30,000 的汽车。

  1. $ node read_gt.js
  2. [ { _id: 5d03e40536943362cffc84a7, name: 'Audi', price: 52642 },
  3. { _id: 5d03e40a36943362cffc84a8, name: 'Mercedes', price: 57127 },
  4. { _id: 5d03e41936943362cffc84ab, name: 'Bentley', price: 350000 },
  5. { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 } ]

这是示例的输出。 仅包括价格超过 30,000 的汽车。

$and逻辑运算符可用于组合多个表达式。

read_gt_lt.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let query = { $and: [{ price: { $gt: 20000 } }, { price: { $lt: 50000 } }] };
  8. db.collection('cars').find(query).toArray().then((docs) => {
  9. console.log(docs);
  10. }).catch((err) => {
  11. console.log(err);
  12. }).finally(() => {
  13. client.close();
  14. });
  15. });

在示例中,我们检索价格在 20,000 到 50,000 之间的汽车。

  1. let query = { $and: [{ price: { $gt: 20000 } }, { price: { $lt: 50000 } }] };

$and运算符将$gt$lt组合在一起以获得结果。

  1. $ node read_gt_lt.js
  2. [ { _id: 5d03e41336943362cffc84aa, name: 'Volvo', price: 29000 },
  3. { _id: 5d03e41e36943362cffc84ac, name: 'Citroen', price: 21000 },
  4. { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 },
  5. { _id: 5d03e42636943362cffc84ae,
  6. name: 'Volkswagen',
  7. price: 21600 } ]

这是示例的输出。

MongoDB 预测

投影确定从数据库传递哪些字段。

projections.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.collection('cars').find({}).project({_id: 0}).toArray().then((docs) => {
  8. console.log(docs);
  9. }).catch((err) => {
  10. console.log(err);
  11. }).finally(() => {
  12. client.close();
  13. });
  14. });

该示例从输出中排除_id字段。

  1. db.collection('cars').find({}).project({_id: 0}).toArray().then((docs) => {

project()方法设置查询的投影; 它不包括_id字段。

  1. $ node projections.js
  2. [ { name: 'Audi', price: 52642 },
  3. { name: 'Mercedes', price: 57127 },
  4. { name: 'Skoda', price: 9000 },
  5. { name: 'Volvo', price: 29000 },
  6. { name: 'Bentley', price: 350000 },
  7. { name: 'Citroen', price: 21000 },
  8. { name: 'Hummer', price: 41400 },
  9. { name: 'Volkswagen', price: 21600 } ]

这是示例的输出。

MongoDB 限制数据输出

limit()方法指定要返回的文档数,skip()方法指定要跳过的文档数。

skip_limit.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. db.collection('cars').find({}).skip(2).limit(5).toArray().then((docs) => {
  8. console.log(docs);
  9. }).catch((err) => {
  10. console.log(err);
  11. }).finally(() => {
  12. client.close();
  13. });
  14. });

该示例从cars集合中读取,跳过前两个文档,并将输出限制为五个文档。

  1. db.collection('cars').find({}).skip(2).limit(5).toArray().then((docs) => {

skip()方法跳过前两个文档,limit()方法将输出限制为五个文档。

  1. $ node skip_limit.js
  2. [ { _id: 5d03e40f36943362cffc84a9, name: 'Skoda', price: 9000 },
  3. { _id: 5d03e41336943362cffc84aa, name: 'Volvo', price: 29000 },
  4. { _id: 5d03e41936943362cffc84ab, name: 'Bentley', price: 350000 },
  5. { _id: 5d03e41e36943362cffc84ac, name: 'Citroen', price: 21000 },
  6. { _id: 5d03e42236943362cffc84ad, name: 'Hummer', price: 41400 } ]

这是示例的输出。

MongoDB 聚合

聚合计算集合中数据的聚合值。

sum_all_cars.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let myagr = [{$group: {_id: 1, all: { $sum: "$price" } }}];
  8. db.collection('cars').aggregate(myagr).toArray().then((sum) => {
  9. console.log(sum);
  10. }).catch((err) => {
  11. console.log(err);
  12. }).finally(() => {
  13. client.close();
  14. });
  15. });

该示例计算集合中所有汽车的价格。

  1. let myagr = [{$group: {_id: 1, all: { $sum: "$price" } }}];

$sum运算符计算并返回数值的总和。 $group运算符通过指定的标识符表达式对输入文档进行分组,并将累加器表达式(如果指定)应用于每个组。

  1. db.collection('cars').aggregate(myagr).toArray().then((sum) => {

aggregate()函数将聚合操作应用于cars集合。

  1. $ node sum_all_cars.js
  2. [ { _id: 1, all: 581769 } ]

所有价格的总和是 581,769。

我们可以使用$match运算符来选择要汇总的特定汽车。

sum_two_cars.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let myagr = [
  8. { $match: { $or: [{ name: "Audi" }, { name: "Volvo" }] } },
  9. { $group: { _id: 1, sum2cars: { $sum: "$price" } } }
  10. ];
  11. db.collection('cars').aggregate(myagr).toArray().then((sum) => {
  12. console.log(sum);
  13. }).catch((err) => {
  14. console.log(err);
  15. }).finally(() => {
  16. client.close();
  17. });
  18. });

该示例计算奥迪和沃尔沃汽车的价格总和。

  1. let myagr = [
  2. { $match: { $or: [{ name: "Audi" }, { name: "Volvo" }] } },
  3. { $group: { _id: 1, sum2cars: { $sum: "$price" } } }
  4. ];

该表达式使用$match$or$group$sum运算符执行任务。

  1. $ node sum_two_cars.js
  2. [ { _id: 1, sum2cars: 81642 } ]

两辆车的价格之和为 81,642。

MongoDB insertOne

insertOne()方法将单个文档插入到集合中。

insert_one.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const ObjectID = mongo.ObjectID;
  4. const url = 'mongodb://localhost:27017';
  5. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  6. if (err) throw err;
  7. const db = client.db("testdb");
  8. let doc = {_id: new ObjectID(), name: "Toyota", price: 37600 };
  9. db.collection('cars').insertOne(doc).then((doc) => {
  10. console.log('Car inserted')
  11. console.log(doc);
  12. }).catch((err) => {
  13. console.log(err);
  14. }).finally(() => {
  15. client.close();
  16. });
  17. });

该示例将一辆汽车插入cars集合。

  1. let doc = {_id: new ObjectID(), name: "Toyota", price: 37600 };

这是要插入的文档。 使用ObjectID生成一个新的 ID。

  1. db.collection('cars').insertOne(doc).then((doc) => {

insertOne()函数将文档插入到集合中。

  1. > db.cars.find({name:'Toyota'})
  2. { "_id" : ObjectId("5d03d4321f9c262a50e671ee"), "name" : "Toyota", "price" : 37600 }

我们用mongo工具确认插入。

MongoDB insertMany()

insertMany()函数可将多个文档插入一个集合中。

insert_many.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const ObjectID = mongo.ObjectID;
  4. const url = 'mongodb://localhost:27017';
  5. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  6. if (err) throw err;
  7. const db = client.db("testdb");
  8. let collection = db.collection('continents');
  9. let continents = [
  10. { _id: new ObjectID(), name: "Africa" }, { _id: new ObjectID(), name: "America" },
  11. { _id: new ObjectID(), name: "Europe" }, { _id: new ObjectID(), name: "Asia" },
  12. { _id: new ObjectID(), name: "Australia" }, { _id: new ObjectID(), name: "Antarctica" }
  13. ];
  14. collection.insertMany(continents).then(result => {
  15. console.log("documents inserted into the collection");
  16. }).catch((err) => {
  17. console.log(err);
  18. }).finally(() => {
  19. client.close();
  20. });
  21. });

该示例创建一个continents集合并将六个文档插入其中。

  1. let collection = db.collection('continents');

collection()方法检索集合; 如果集合不存在,则会创建它。

  1. let continents = [
  2. { _id: new ObjectID(), name: "Africa" }, { _id: new ObjectID(), name: "America" },
  3. { _id: new ObjectID(), name: "Europe" }, { _id: new ObjectID(), name: "Asia" },
  4. { _id: new ObjectID(), name: "Australia" }, { _id: new ObjectID(), name: "Antarctica" }
  5. ];

这是要插入新集合的六个记录的数组。 ObjectID()创建一个新的 ObjectID,这是用于标识文档的唯一值,而不是整数。

  1. collection.insertMany(continents).then(result => {
  2. console.log("documents inserted into the collection");
  3. }).catch((err) => {
  4. console.log(err);
  5. }).finally(() => {
  6. client.close();
  7. });

insertMany()方法将文档数组插入continents集合。

  1. > db.continents.find()
  2. { "_id" : ObjectId("5cfcf97732fc4913748c9669"), "name" : "Africa" }
  3. { "_id" : ObjectId("5cfcf97732fc4913748c966a"), "name" : "America" }
  4. { "_id" : ObjectId("5cfcf97732fc4913748c966b"), "name" : "Europe" }
  5. { "_id" : ObjectId("5cfcf97732fc4913748c966c"), "name" : "Asia" }
  6. { "_id" : ObjectId("5cfcf97732fc4913748c966d"), "name" : "Australia" }
  7. { "_id" : ObjectId("5cfcf97732fc4913748c966e"), "name" : "Antarctica" }

continents集合已成功创建。

MongoDB deleteOne

deleteOne()方法用于删除文档。

delete_one.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let query = { name: "Volkswagen" };
  8. db.collection('cars').deleteOne(query).then((result) => {
  9. console.log('Car deleted');
  10. console.log(result);
  11. }).catch((err) => {
  12. console.log(err);
  13. }).finally(() => {
  14. client.close();
  15. });
  16. });

该示例删除文档。

  1. let query = { name: "Volkswagen" };
  2. db.collection('cars').deleteOne(query).then((result) => {
  3. ...

deleteOne()删除Volkswagen的文档。

MongoDB updateOne()

updateOne()函数用于更新文档。

update_one.js

  1. const mongo = require('mongodb');
  2. const MongoClient = mongo.MongoClient;
  3. const url = 'mongodb://localhost:27017';
  4. MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  5. if (err) throw err;
  6. const db = client.db("testdb");
  7. let filQuery = { name: "Audi" };
  8. let updateQuery = { $set: { "price": 52000 }};
  9. db.collection('cars').updateOne(filQuery, updateQuery).then(result => {
  10. console.log('Car updated');
  11. console.log(result);
  12. }).catch((err) => {
  13. console.log(err);
  14. }).finally(() => {
  15. client.close();
  16. });
  17. });

该示例更新了汽车的价格。

  1. let filQuery = { name: "Audi" };
  2. let updateQuery = { $set: { "price": 52000 }};
  3. db.collection('cars').updateOne(filQuery, updateQuery).then(result => {

通过updateOne()方法将 Audi 的价格更改为 52,000。 $set运算符用于更改价格。

  1. > db.cars.find({name:'Audi'})
  2. { "_id" : ObjectId("5cfcfc3438f62aaa09b52175"), "name" : "Audi", "price" : 52000 }

我们使用mongo工具确认更改。

在本教程中,我们使用了 MongoDB 和 JavaScript。 列出所有 JavaScript 教程。