Adding data to MongoDB
Before updating a collection, one obviously needs to insert data in it. The insert() method will create a new record:
db.products.insert( { item: "card", qty: 15 } )
An _id (primary key) value will be added automatically if not specified. If the primary key is specified but a document with that value already exist, you'll get an error:
> var card = db.products.findOne({"item": "card"}) > db.products.insert(card) E11000 duplicate key error index: dek.products.$_id_ dup key: { : ObjectId('5194973a65642aa95f1eb40f') }
If you want to insert a document (if new) or update an existing one, Mongo provides a useful wrapper around insert() and update(), the save() method:
> card.qty-=1 14 > db.products.save(card) > db.products.findOne() { "_id" : ObjectId("5194973a65642aa95f1eb40f"), "item" : "card", "qty" : 14 }















