Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để thêm một cột trong bộ sưu tập MongoDB?

Để thêm một cột, bạn cần cập nhật bộ sưu tập. Cú pháp như sau -

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

Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với các tài liệu -

> 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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

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

Điều này sẽ tạo ra kết quả sau -

{
   "_id" : ObjectId("5e04d66af5e889d7a519950f"),
   "StudentId" : 101,
   "StudentName" : "Chris"
}
{
   "_id" : ObjectId("5e04d673f5e889d7a5199510"),
   "StudentId" : 102,
   "StudentName" : "Robert"
}
{
   "_id" : ObjectId("5e04d67bf5e889d7a5199511"),
   "StudentId" : 103,
   "StudentName" : "David"
}

Đây là truy vấn để thêm một cột trong MongoDB -

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

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

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

Điều này sẽ tạo ra kết quả sau -

{
   "_id" : ObjectId("5e04d66af5e889d7a519950f"),
   "StudentId" : 101,
   "StudentName" : "Chris",
   "StudentCityName" : "New York"
}
{
   "_id" : ObjectId("5e04d673f5e889d7a5199510"),
   "StudentId" : 102,
   "StudentName" : "Robert",
   "StudentCityName" : "New York"
}
{
   "_id" : ObjectId("5e04d67bf5e889d7a5199511"),
   "StudentId" : 103,
   "StudentName" : "David",
   "StudentCityName" : "New York"
}