Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Thêm cột (trường) mới vào collection MongoDB

Để thêm trường mới cho tất cả tài liệu, dùng update() với $set và multi: true. Cú pháp:

db.getCollection("yourCollection").update({}, {$set: {"yourField": "yourValue"}}, false, true);

Tạo collection:

> db.addColumnDemo.insertOne({"StudentId":101,"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04d66af5e889d7a519950f") }
> db.addColumnDemo.insertOne({"StudentId":102,"StudentName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04d673f5e889d7a5199510") }
> db.addColumnDemo.insertOne({"StudentId":103,"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04d67bf5e889d7a5199511") }

Hiển thị tài liệu:

> db.addColumnDemo.find().pretty();

Thêm trường StudentCityName = "New York" cho tất cả tài liệu:

> db.getCollection('addColumnDemo').update({}, {$set: {"StudentCityName": "New York"}}, false, true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Kết quả - tất cả 3 tài liệu có thêm trường mới:

{ "_id" : ObjectId("5e04d66a..."), "StudentId" : 101, "StudentName" : "Chris", "StudentCityName" : "New York" }
{ "_id" : ObjectId("5e04d673..."), "StudentId" : 102, "StudentName" : "Robert", "StudentCityName" : "New York" }
{ "_id" : ObjectId("5e04d67b..."), "StudentId" : 103, "StudentName" : "David", "StudentCityName" : "New York" }

Lưu ý: Tham số 3 (upsert=false), tham số 4 (multi=true). Từ MongoDB 3.2+, dùng updateMany({}, {$set: {"StudentCityName": "New York"}}). MongoDB schema-less nên thêm trường rất linh hoạt.