Tạo collection với một tài liệu:
> db.replacingEntireDocumentDemo.insertOne({
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentCountryName": "US"
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3119bb64f4b851c3a13e8") }
Hiển thị tài liệu
> db.replacingEntireDocumentDemo.find().pretty();
Thay thế toàn bộ tài liệu (không dùng $set)
> db.replacingEntireDocumentDemo.update(
{"StudentFirstName": "John", "StudentLastName": "Smith", "StudentCountryName": "US"},
{"StudentFirstName": "David", "StudentLastName": "Miller", "StudentCountryName": "AUS"}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Kết quả
> db.replacingEntireDocumentDemo.find().pretty();
Kết quả (toàn bộ tài liệu đã thay đổi, _id giữ nguyên):
{
"_id": ObjectId("5cd3119bb64f4b851c3a13e8"),
"StudentFirstName": "David",
"StudentLastName": "Miller",
"StudentCountryName": "AUS"
}
Cảnh báo: Cách này thay thế hoàn toàn tài liệu (trừ _id). Mọi trường không có trong đối tượng mới sẽ bị xóa. Thông thường nên dùng $set để cập nhật một phần.