Phương thức save() trong MongoDB shell cho phép lưu đối tượng JavaScript và tự động cập nhật biến đó với _id đã sinh.
Cú pháp:
var anyVaribaleName=yourValue db.anyCollectionName.save(yourVariableName); yourVariableName;
Tạo đối tượng:
> var studentDetails={"StudentName":"Chris","ListOfMarks":[56,78,89],"ListOfSubject":["MySQL","Java","MongoDB"]};
Lưu vào collection demo40:
> db.demo40.save(studentDetails);
WriteResult({ "nInserted" : 1 })
Hiển thị biến studentDetails (đã có _id):
> studentDetails;
{
"StudentName" : "Chris",
"ListOfMarks" : [ 56, 78, 89 ],
"ListOfSubject" : [ "MySQL", "Java", "MongoDB" ],
"_id" : ObjectId("5e177757cfb11e5c34d898e2")
}
Lưu ý quan trọng:
save()là phương thức của mongo shell, không phải driver- Nếu đối tượng đã có _id →
upsert(cập nhật nếu tồn tại, chèn nếu không) - Nếu chưa có _id → chèn mới và gán _id vào biến
- Trong driver (Node.js, Python...), dùng
insertOne()và lấyinsertedIdtừ kết quả