Khi collection chưa tồn tại, MongoDB tự động tạo collection trong quá trình tạo index. Trường createdCollectionAutomatically cho biết thao tác đã tạo mới collection.
Ví dụ tạo index trên collection chưa tồn tại
> db.createCollectionDemo.createIndex({"ClientCountryName":1});
Kết quả:
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Thêm tài liệu
> db.createCollectionDemo.insertOne({"ClientName":"Larry","ClientCountryName":"US"});
{ "acknowledged": true, "insertedId": ObjectId("5cd2950be3526dbddbbfb612") }
Hiển thị tài liệu
> db.createCollectionDemo.find().pretty();
Kết quả:
{
"_id": ObjectId("5cd2950be3526dbddbbfb612"),
"ClientName": "Larry",
"ClientCountryName": "US"
}
Giải thích: createdCollectionAutomatically: true có nghĩa là collection createCollectionDemo không tồn tại trước lệnh createIndex(), nên MongoDB đã tạo nó tự động. Nếu collection đã tồn tại, giá trị sẽ là false.