如何在 MongoDB 中向現有記錄新增欄位?
可以使用 update 指令向現有記錄新增欄位。讓我們首先建立一個包含文件的集合 -
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00e32588d4a6447b2e061")
}
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00e59588d4a6447b2e062")
}以下是要在 find() 方法的幫助下從集合中顯示所有文件的查詢 -
> db.addAFieldToEveryRecordDemo.find().pretty();
將會產生以下輸出 -
{
"_id" : ObjectId("5cd00e32588d4a6447b2e061"),
"ClientName" : "Chris",
"ClientAge" : 34
}
{
"_id" : ObjectId("5cd00e59588d4a6447b2e062"),
"ClientName" : "Robert",
"ClientAge" : 36
}以下是向每條記錄新增欄位的查詢。我們要新增 ClientDetails -
>db.addAFieldToEveryRecordDemo.update({},{$set:{"ClientDetails.ClientCountryName":""}},true,true);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })讓我們檢查所有文件是否已添加了新記錄 -
> db.addAFieldToEveryRecordDemo.find().pretty();
將會產生以下輸出 -
{
"_id" : ObjectId("5cd00e32588d4a6447b2e061"),
"ClientName" : "Chris",
"ClientAge" : 34,
"ClientDetails" : {
"ClientCountryName" : ""
}
}
{
"_id" : ObjectId("5cd00e59588d4a6447b2e062"),
"ClientName" : "Robert",
"ClientAge" : 36,
"ClientDetails" : {
"ClientCountryName" : ""
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP