Tutorial by Examples

db.people.insert({name: 'Tom', age: 28}); Or db.people.save({name: 'Tom', age: 28}); The difference with save is that if the passed document contains an _id field, if a document already exists with that _id it will be updated instead of being added as new. Two new methods to insert documents...
Update the entire object: db.people.update({name: 'Tom'}, {age: 29, name: 'Tom'}) // New in MongoDB 3.2 db.people.updateOne({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace only first matching document. db.people.updateMany({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace all matchin...
Deletes all documents matching the query parameter: // New in MongoDB 3.2 db.people.deleteMany({name: 'Tom'}) // All versions db.people.remove({name: 'Tom'}) Or just one // New in MongoDB 3.2 db.people.deleteOne({name: 'Tom'}) // All versions db.people.remove({name: 'Tom'}, true) M...
Query for all the docs in the people collection that have a name field with a value of 'Tom': db.people.find({name: 'Tom'}) Or just the first one: db.people.findOne({name: 'Tom'}) You can also specify which fields to return by passing a field selection parameter. The following will exclude t...
You can use other operators besides $set when updating a document. The $push operator allows you to push a value into an array, in this case we will add a new nickname to the nicknames array. db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}}) // This adds the string 'Tommy' into the n...
To update multiple documents in a collection, set the multi option to true. db.collection.update( query, update, { upsert: boolean, multi: boolean, writeConcern: document } ) multi is optional. If set to true, updates multiple documents that meet the query crit...
For the following schema: {name: 'Tom', age: 28, marks: [50, 60, 70]} Update Tom's marks to 55 where marks are 50 (Use the positional operator $): db.people.update({name: "Tom", marks: 50}, {"$set": {"marks.$": 55}}) For the following schema: {name: 'Tom', age:...

Page 1 of 1