- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境設定
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥函式概念
- Node.js - 上傳檔案
- Node.js - 傳送郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTful API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 從表中選擇資料
- Node.js - MySQL Where 條件
- Node.js - MySQL 排序
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL 聯接
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新
- Node.js - MongoDB 限制結果
- Node.js - MongoDB 聯接
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
Node.js - MongoDB 更新
更新操作指的是修改 MongoDB 集合中文件的一個或多個欄位的值。Node.js 的 mongodb 驅動程式定義了 updateOne() 和 updateMany() 方法。updateOne() 方法用於修改單個文件,而 updateMany() 方法用於更新多個文件。
updateOne() 方法的語法如下:
collection.updateOne(query, values);
query 引數用於查詢要更新的目標文件。values 引數包含用於修改文件的鍵值對。updateMany() 方法遵循相同的語法,只是查詢從集合中返回多個文件。
updateOne()
以下示例更改了 ProductID 為 3 的文件的價格。$set 運算子將新值賦給 price 欄位。
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb://:27017/";
const client = new MongoClient(uri);
try {
await client.connect();
await sortdocs(client, "mydb", "products");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function sortdocs(client, dbname, colname){
var qry = { ProductID: 3 };
var vals = { $set: { Name: "Router", price: 2750 } };
const result = await client.db(dbname).collection(colname).updateOne(qry, vals);
console.log("Document updated");
}
要驗證文件是否已更新,請使用 Mongosh shell 並輸入以下命令:
> use mydb
< switched to db mydb
> db.products.find({"ProductID":3})
{
_id: ObjectId("6580964f20f979d2e9a72ae9"),
ProductID: 3,
Name: 'Router',
price: 2750
}
updateMany()
假設 products 集合包含以下名稱以“er”結尾的文件。
以下 sortdocs() 函式將所有上述產品的價格增加 125 元。我們使用了 $inc 運算子。
示例
async function sortdocs(client, dbname, colname){
var qry = {Name: /er$/};
var vals = { $inc: { price: 125 } };
const result = await client.db(dbname).collection(colname).updateMany(qry, vals);
console.log("Documents updated");
}
輸出
廣告
