What is the difference between db.collection_name.insert({…data}) and db.collection_name.save({…data})?
Creating MongoDB objects happens either with insert or save methods. Although insert method is now deprecated, it can still be used in creating documents. MongoDB has introduced insertOne, insertMany methods in place of insert method. Insert method can be used to insert either one or multiple records.
To insert single record,
db.customers.insert({firstName: "Sara", lastName: "Negash", phone: "09xxxxxxxx"})
To insert multiple records
db.customers.insert([ {firstName: "Abebe1",lastName: "Mulaw1",phone: "09xxxxxxxx"}, {firstName: "Abebe2",lastName: "Mulaw2",phone: "092xxxxxxxx"}, {firstName: "Abebe3",lastName: "Mulaw3",phone: "093xxxxxxxx"} ])
To such solution, MongoDB introduced two newer methods which are insertOne and insertMany after version 3.2.
To insert single record,
db.customers.insertOne({firstName: "Dinku", lastName: "Ayele", phone: "09xxxxxxxx"})
To insert multiple records,
db.customers.insertMany([ {firstName: "Abebe1",lastName: "Mulaw1",phone: "09xxxxxxxx"}, {firstName: "Abebe2",lastName: "Mulaw2",phone: "092xxxxxxxx"}, {firstName: "Abebe3",lastName: "Mulaw3",phone: "093xxxxxxxx"} ])
In the case of save method, this method uses either insert or update command.
If the document contains an _id field, the save method calls the update method and if there is no _id field then it will call the insert method. To create a new document,
db.customers.save({firstName: "Abebe1",lastName: "Mulaw1",phone: "092222xxxxxx})
To update document,
db.customers.save({_id: "274328364", firstName: "Helen",lastName: "Abebe",phone: "092222xxxxxx})