Để chèn tài liệu mới, dùng insert() hoặc save().
Trường hợp 1: Dùng insert().
db.yourCollectionName.insert(yourDocument);
Trường hợp 2: Dùng save().
db.yourCollectionName.save(yourDocument);
Nếu collection chưa tồn tại, MongoDB sẽ tự tạo mới.
Ví dụ insert():
> db.userInformation.insert({ "Name":"John", "Age":30, "isStudent":false, "Subjects":["Introduction to java","Introduction to MongoDB"] });
WriteResult({ "nInserted" : 1 })
Collection userInformation đã tồn tại nên không tạo mới.
Ví dụ save():
> db.employee.save({"EmployeeName":"Larry","Salary":180000,"Age":25, "Address":({"CountryName":"US","CityName":"New York"}) });
WriteResult({ "nInserted" : 1 })
Collection employee chưa có, MongoDB tự tạo và chèn tài liệu.
Kiểm tra danh sách collection:
> show collections; employee userInformation