CP3 Creating, Updating, and Deleting Documents
This chapter covers the basic of moving data into and out of the database,including the following:
- Adding new documents to a collection
- Removing documents from a collection
- Updating existing documents
- Choosing the correct level of safety versus speed for all of these operations
Inserting Documents
Insert are the basic method for adding data to MongoDB. To insert a single document,use the collection's insertOne method.
>? > db.movies.insertOne({"title":"Stand by Me"}) { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedId" : ObjectId("624b7c74678b91f736a41441") } >?
insertMany
If you need to insert multiple documents into a collection, you can use insertMany. insertMany enables you to pass an array of documents to the database.
>? > db.movies.drop() true > db.movies.insertMany([{"title" : "Ghostbusters"}, ... {"title" : "E.T."}, ... {"title" : "Blade Runner"}]); { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedIds" : [ ? ? ? ? ? ? ? ? ObjectId("624b7e4e678b91f736a41442"), ? ? ? ? ? ? ? ? ObjectId("624b7e4e678b91f736a41443"), ? ? ? ? ? ? ? ? ObjectId("624b7e4e678b91f736a41444") ? ? ? ? ] } > db.movies.find().pretty() { "_id" : ObjectId("624b7e4e678b91f736a41442"), "title" : "Ghostbusters" } { "_id" : ObjectId("624b7e4e678b91f736a41443"), "title" : "E.T." } { "_id" : ObjectId("624b7e4e678b91f736a41444"), "title" : "Blade Runner" } >
For ordered inserts, the array passed to insertMany defines the insertion order.If a document produces an insertion error,no documents beyond that point in the array will be inserted.
For unordered inserts,MongoDB will attempt to insert all documents, regardless of whether some insertions produce errors.
> db.movies.insertMany([ ... {"_id" : 0, "title" : "Top Gun"}, ... {"_id" : 1, "title" : "Back to the Future"}, ... {"_id" : 1, "title" : "Gremlins"}, ... {"_id" : 2, "title" : "Aliens"}]) uncaught exception: BulkWriteError({ ? ? ? ? "writeErrors" : [ ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? "index" : 2, ? ? ? ? ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: video.movies index: _id_ dup key: { _id: 1.0 }", ? ? ? ? ? ? ? ? ? ? ? ? "op" : { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "_id" : 1, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "title" : "Gremlins" ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ], ? ? ? ? "writeConcernErrors" : [ ], ? ? ? ? "nInserted" : 2, ? ? ? ? "nUpserted" : 0, ? ? ? ? "nMatched" : 0, ? ? ? ? "nModified" : 0, ? ? ? ? "nRemoved" : 0, ? ? ? ? "upserted" : [ ] }) : BulkWriteError({ ? ? ? ? "writeErrors" : [ ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? "index" : 2, ? ? ? ? ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: video.movies index: _id_ dup key: { _id: 1.0 }", ? ? ? ? ? ? ? ? ? ? ? ? "op" : { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "_id" : 1, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "title" : "Gremlins" ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ], ? ? ? ? "writeConcernErrors" : [ ], ? ? ? ? "nInserted" : 2, ? ? ? ? "nUpserted" : 0, ? ? ? ? "nMatched" : 0, ? ? ? ? "nModified" : 0, ? ? ? ? "nRemoved" : 0, ? ? ? ? "upserted" : [ ] }) BulkWriteError@src/mongo/shell/bulk_api.js:367:48 BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:332:24 Bulk/this.execute@src/mongo/shell/bulk_api.js:1186:23 DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:326:5 @(shell):1:1 >?
If instead we specify unordered inserts,the first,second,and fourth documents in the array are inserted. The only insert that fails is the third document,again because of a duplicate "_id" error:
>? > db.movies.insertMany([ ... {"_id" : 3, "title" : "Sixteen Candles"}, ... {"_id" : 4, "title" : "The Terminator"}, ... {"_id" : 4, "title" : "The Princess Bride"}, ... {"_id" : 5, "title" : "Scarface"}], ... {"ordered" : false})? uncaught exception: BulkWriteError({ ? ? ? ? "writeErrors" : [ ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? "index" : 2, ? ? ? ? ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: video.movies index: _id_ dup key: { _id: 4.0 }", ? ? ? ? ? ? ? ? ? ? ? ? "op" : { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "_id" : 4, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "title" : "The Princess Bride" ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ], ? ? ? ? "writeConcernErrors" : [ ], ? ? ? ? "nInserted" : 3, ? ? ? ? "nUpserted" : 0, ? ? ? ? "nMatched" : 0, ? ? ? ? "nModified" : 0, ? ? ? ? "nRemoved" : 0, ? ? ? ? "upserted" : [ ] }) : BulkWriteError({ ? ? ? ? "writeErrors" : [ ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? "index" : 2, ? ? ? ? ? ? ? ? ? ? ? ? "code" : 11000, ? ? ? ? ? ? ? ? ? ? ? ? "errmsg" : "E11000 duplicate key error collection: video.movies index: _id_ dup key: { _id: 4.0 }", ? ? ? ? ? ? ? ? ? ? ? ? "op" : { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "_id" : 4, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "title" : "The Princess Bride" ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ], ? ? ? ? "writeConcernErrors" : [ ], ? ? ? ? "nInserted" : 3, ? ? ? ? "nUpserted" : 0, ? ? ? ? "nMatched" : 0, ? ? ? ? "nModified" : 0, ? ? ? ? "nRemoved" : 0, ? ? ? ? "upserted" : [ ] }) BulkWriteError@src/mongo/shell/bulk_api.js:367:48 BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:332:24 Bulk/this.execute@src/mongo/shell/bulk_api.js:1186:23 DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:326:5 @(shell):1:1 >?
Insert Validation
- Check the document's basic structure and adds an "_id" field if one does not exist.
- One of the basic structure checks is size: all documents must be smaller than 16MB.
Removing Document
The CRUD API provides deleteOne and deleteMany for this purpose.
deleteOne will delete the first document found that matches the filter.?
>? > db.movies.find() { "_id" : 0, "title" : "Top Gun" } { "_id" : 1, "title" : "Back to the Future" } { "_id" : 3, "title" : "Sixteen Candles" } { "_id" : 4, "title" : "The Terminator" } { "_id" : 5, "title" : "Scarface" } > db.movies.deleteOne({"_id": 4}) { "acknowledged" : true, "deletedCount" : 1 } > db.movies.find() { "_id" : 0, "title" : "Top Gun" } { "_id" : 1, "title" : "Back to the Future" } { "_id" : 3, "title" : "Sixteen Candles" } { "_id" : 5, "title" : "Scarface" } >
To delete all the documents that match a filter,use deleteMany:
> db.movies.find() { "_id" : 0, "title" : "Top Gun", "year" : 1986 } { "_id" : 1, "title" : "Back to the Future", "year" : 1985 } { "_id" : 3, "title" : "Sixteen Candles", "year" : 1984 } { "_id" : 4, "title" : "The Terminator", "year" : 1984 } { "_id" : 5, "title" : "Scarface", "year" : 1983 } > db.movies.deleteMany({"year":1984}) { "acknowledged" : true, "deletedCount" : 2 } > db.movies.find() { "_id" : 0, "title" : "Top Gun", "year" : 1986 } { "_id" : 1, "title" : "Back to the Future", "year" : 1985 } { "_id" : 5, "title" : "Scarface", "year" : 1983 } >? ?
drop
It is possible to use deleteMany to remove all documents in a collection:
> db.movies.find() > db.movies.insertMany([ ... {"_id" : 0, "title" : "Top Gun","year":1986}, ... {"_id" : 1, "title" : "Back to the Future","year":1985}, ... {"_id" : 3, "title" : "Sixteen Candles","year":1984}, ... {"_id" : 4, "title" : "The Terminator","year": 1984}, ... {"_id" : 5, "title" : "Scarface","year": 1983}]) { "acknowledged" : true, "insertedIds" : [ 0, 1, 3, 4, 5 ] } > db.movies.find() { "_id" : 0, "title" : "Top Gun", "year" : 1986 } { "_id" : 1, "title" : "Back to the Future", "year" : 1985 } { "_id" : 3, "title" : "Sixteen Candles", "year" : 1984 } { "_id" : 4, "title" : "The Terminator", "year" : 1984 } { "_id" : 5, "title" : "Scarface", "year" : 1983 } > db.movies.deleteMany({}) { "acknowledged" : true, "deletedCount" : 5 } > db.movies.find()
Removing document is usually a fairly quick operation.However ,if you want to clear an entire collection,it is faster to drop it:
> db.movies.find() >? > db.movies.insertMany([ ... {"_id" : 0, "title" : "Top Gun","year":1986}, ... {"_id" : 1, "title" : "Back to the Future","year":1985}, ... {"_id" : 3, "title" : "Sixteen Candles","year":1984}, ... {"_id" : 4, "title" : "The Terminator","year": 1984}, ... {"_id" : 5, "title" : "Scarface","year": 1983}]) { "acknowledged" : true, "insertedIds" : [ 0, 1, 3, 4, 5 ] } > db.movies.find() { "_id" : 0, "title" : "Top Gun", "year" : 1986 } { "_id" : 1, "title" : "Back to the Future", "year" : 1985 } { "_id" : 3, "title" : "Sixteen Candles", "year" : 1984 } { "_id" : 4, "title" : "The Terminator", "year" : 1984 } { "_id" : 5, "title" : "Scarface", "year" : 1983 } > db.movies.drop() true >?
Updating Documents
Once a document is stored in the database,it can be changed using one of several update methods: updateOne,updateMany,and replaceOne
Document Replacement
replaceOne fully replaces a matching document with a new one.
> use users switched to db users >? > db.users.insertOne({ ... ?"_id" : ObjectId("4b2b9f67a1f631733d917a7a"), ... ?"name" : "joe", ... ?"friends" : 32, ... ?"enemies" : 2 ... }); { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedId" : ObjectId("4b2b9f67a1f631733d917a7a") } >? > var joe = db.users.findOne({"name": "joe"}); > joe.relationships = {"friends": joe.friends,"enemies":joe.enemies}; { "friends" : 32, "enemies" : 2 }
> joe.username = joe.name; joe > delete joe.friends; true > delete joe.enemies; true > delete joe.name; true > db.users.replaceOne({"name":"joe"}, joe); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >? doing a findOne shows that the structure of the document has been updated:
> db.people.insertMany([ ... {"name" : "joe", "age" : 65}, ... {"name" : "joe", "age" : 20}, ... {"name" : "joe", "age" : 49} ... ]) { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedIds" : [ ? ? ? ? ? ? ? ? ObjectId("624bf1357ee8daa72c1abadb"), ? ? ? ? ? ? ? ? ObjectId("624bf1357ee8daa72c1abadc"), ? ? ? ? ? ? ? ? ObjectId("624bf1357ee8daa72c1abadd") ? ? ? ? ] } > db.people.find().pretty() { "_id" : ObjectId("624bf1357ee8daa72c1abadb"), "name" : "joe", "age" : 65 } { "_id" : ObjectId("624bf1357ee8daa72c1abadc"), "name" : "joe", "age" : 20 } { "_id" : ObjectId("624bf1357ee8daa72c1abadd"), "name" : "joe", "age" : 49 } > joe = db.people.findOne({"name": "joe","age": 20}); { "_id" : ObjectId("624bf1357ee8daa72c1abadc"), "name" : "joe", "age" : 20 } > joe.age++; 20
Using Update Operators
>? > db.analytics.insertOne({ ... ?"_id" : ObjectId("4b253b067525f35f94b60a31"), ... ?"url" : "www.example.com", ... ?"pageviews" : 52 ... }); { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedId" : ObjectId("4b253b067525f35f94b60a31") } >? > db.analytics.updateOne({"url":"www.example.com"},{"$inc":{"pageviews": 1}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.analytics.findOne() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "url" : "www.example.com", ? ? ? ? "pageviews" : 53 } >?
Every time someone visists a page,we can find the page by its URL and the "$inc" modifier to increment the value of the ""pageviews" key.
Getting started with the "$set" modifer
"$set" sets the value of a field.
> db.users.find() >? > db.users.insertOne({ ?"_id" : ObjectId("4b253b067525f35f94b60a31"), ?"name" : "joe", ?"age" : 30, ?"sex" : "male", ?"location" : "Wisconsin"}); { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedId" : ObjectId("4b253b067525f35f94b60a31") } > db.users.find() { "_id" : ObjectId("4b253b067525f35f94b60a31"), "name" : "joe", "age" : 30, "sex" : "male", "location" : "Wisconsin" } > db.users.find().pretty() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "name" : "joe", ? ? ? ? "age" : 30, ? ? ? ? "sex" : "male", ? ? ? ? "location" : "Wisconsin" } > db.users.updateOne({"_id" : ObjectId("4b253b067525f35f94b60a31")},{"$set" : {"favorite book" : "War and Peace"}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >? > db.users.findOne() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "name" : "joe", ? ? ? ? "age" : 30, ? ? ? ? "sex" : "male", ? ? ? ? "location" : "Wisconsin", ? ? ? ? "favorite book" : "War and Peace" } > db.users.updateOne({"name":"joe"},{"$set" : {"favorite book" : "Green Eggs and Ham"}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >? > db.users.findOne() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "name" : "joe", ? ? ? ? "age" : 30, ? ? ? ? "sex" : "male", ? ? ? ? "location" : "Wisconsin", ? ? ? ? "favorite book" : "Green Eggs and Ham" }
> db.users.updateOne({"name" : "joe"},{"$set" : {"favorite book" : ["Cat's Cradle", "Foundation Trilogy","Ender's Game"]}}); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.users.findOne() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "name" : "joe", ? ? ? ? "age" : 30, ? ? ? ? "sex" : "male", ? ? ? ? "location" : "Wisconsin", ? ? ? ? "favorite book" : [ ? ? ? ? ? ? ? ? "Cat's Cradle", ? ? ? ? ? ? ? ? "Foundation Trilogy", ? ? ? ? ? ? ? ? "Ender's Game" ? ? ? ? ] } >? > db.users.updateOne({"name" : "joe"},{"$set" :{"favorite book":["Cat's Cradle","Foundation Trilogy","Ender's Game"]}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 } > db.users.findOne() { ? ? ? ? "_id" : ObjectId("4b253b067525f35f94b60a31"), ? ? ? ? "name" : "joe", ? ? ? ? "age" : 30, ? ? ? ? "sex" : "male", ? ? ? ? "location" : "Wisconsin", ? ? ? ? "favorite book" : [ ? ? ? ? ? ? ? ? "Cat's Cradle", ? ? ? ? ? ? ? ? "Foundation Trilogy", ? ? ? ? ? ? ? ? "Ender's Game" ? ? ? ? ] } > db.users.updateOne({"name" : "joe"},{"$unset" :{"favorite book" : 1}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >?
Incrementing and decrementing
The "$inc" operator can be used to change the value for an existing key or to create a new key if it does not already exist.
> db.games.updateOne({"game": "pinball","user": "joe"},{"$inc": {"score" : 50}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } > db.games.findOne() { ? ? ? ? "_id" : ObjectId("624c2be7dee35be136554631"), ? ? ? ? "game" : "pinball", ? ? ? ? "user" : "joe", ? ? ? ? "score" : 100 } > db.games.updateOne({"game": "pinball","user": "joe"},{"$inc" : {"score" : 10000}}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } >? > db.games.findOne() { ? ? ? ? "_id" : ObjectId("624c2be7dee35be136554631"), ? ? ? ? "game" : "pinball", ? ? ? ? "user" : "joe", ? ? ? ? "score" : 10100 } > db.strcounts.insert({"count": "1"}) WriteResult({ "nInserted" : 1 }) > db.strcounts.update({},{"$inc": {"count" : 1}}) WriteResult({ ? ? ? ? "nMatched" : 0, ? ? ? ? "nUpserted" : 0, ? ? ? ? "nModified" : 0, ? ? ? ? "writeError" : { ? ? ? ? ? ? ? ? "code" : 14, ? ? ? ? ? ? ? ? "errmsg" : "Cannot apply $inc to a value of non-numeric type. {_id: ObjectId('624c34c0dee35be136554632')} has the field 'count' of non-numeric type string" ? ? ? ? } }) >?
Array operator?
An extensive class of update operators exists for manipulating arrays.
Adding elements
"$push" adds elements to the end of an array if the array exists and create a new array if it does not.
Updating Multiple Documents
updateOne updates only the first document found that matches the filter criteria.
updateMany follows the same semantics as updateOne and takes the same parameters.The key difference is in the number of document that might be changed.
updateMany provides a powerful tool for performing schema migrations or rolling out new features to certain users.
>? > db.users.insertMany([ ... {birthday: "10/13/1978"}, ... {birthday: "10/13/1978"}, ... {birthday: "10/13/1978"}]); { ? ? ? ? "acknowledged" : true, ? ? ? ? "insertedIds" : [ ? ? ? ? ? ? ? ? ObjectId("624cc4daf1b493284d85d20d"), ? ? ? ? ? ? ? ? ObjectId("624cc4daf1b493284d85d20e"), ? ? ? ? ? ? ? ? ObjectId("624cc4daf1b493284d85d20f") ? ? ? ? ] } > db.users.find() { "_id" : ObjectId("624cc4daf1b493284d85d20d"), "birthday" : "10/13/1978" } { "_id" : ObjectId("624cc4daf1b493284d85d20e"), "birthday" : "10/13/1978" } { "_id" : ObjectId("624cc4daf1b493284d85d20f"), "birthday" : "10/13/1978" } > db.users.updateMany({"birthday" : "10/13/1978"},{"$set":{"gift": "Happy Birthday!"}}) { "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 } > db.users.find() { "_id" : ObjectId("624cc4daf1b493284d85d20d"), "birthday" : "10/13/1978", "gift" : "Happy Birthday!" } { "_id" : ObjectId("624cc4daf1b493284d85d20e"), "birthday" : "10/13/1978", "gift" : "Happy Birthday!" } { "_id" : ObjectId("624cc4daf1b493284d85d20f"), "birthday" : "10/13/1978", "gift" : "Happy Birthday!" } >
Returning Updated Documents
findOneAndDelete, findOneAndReplace,findOneAndUpdate
|