Trong MongoDB, không có khái niệm "cột" (column) vì MongoDB là cơ sở dữ liệu khôngschema (schema-less) và không chứa bảng (table). Thay vào đó, MongoDB sử dụng khái niệm collection (tập hợp), và một collection có thể chứa các tài liệu (document) với các trường khác nhau.
Cú pháp chèn tài liệu:
db.yourCollectionName.insertOne({"YourFieldName": yourValue, "yourFieldName": "yourValue", ... N});
Để lấy một bản ghi đơn lẻ, sử dụng findOne(); để lấy tất cả bản ghi, sử dụng find():
db.yourCollectionName.findOne(); // Lấy 1 bản ghi db.yourCollectionName.find(); // Lấy tất cả bản ghi
Ví dụ minh họa:
Tạo collection với các tài liệu có cấu trúc khác nhau:
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Larry"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953b98749816a0ce933682") }
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"David","UserAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953ba4749816a0ce933683") }
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Carol","UserAge":25,"UserCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953bb8749816a0ce933684") }
Hiển thị tất cả tài liệu bằng find():
> db.collectionOnDifferentDocumentDemo.find();
Kết quả:
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c953ba4749816a0ce933683"), "UserName" : "David", "UserAge" : 24 }
{ "_id" : ObjectId("5c953bb8749816a0ce933684"), "UserName" : "Carol", "UserAge" : 25, "UserCountryName" : "US" }
Hiển thị một bản ghi đơn lẻ bằng findOne():
> db.collectionOnDifferentDocumentDemo.findOne();
Kết quả:
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
Lưu ý: Vì MongoDB không có schema cố định, các tài liệu trong cùng một collection có thể có các trường khác nhau. Để "lấy tên cột", bạn thực chất là đang lấy các khóa (keys) xuất hiện trong các tài liệu.