> // the old insert API > db.test.insert({_id: 1}) WriteResult({ "nInserted" : 1 }) > db.test.insert([{_id: 2}, {_id: 3}, {_id: 4}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
The new API better distinguishes single- and bulk-insert, and returns more useful results:
> // the new CRUD API > db.test2.insertOne({_id: 1}) { "acknowledged" : true, "insertedId" : 1 } > db.test2.insertMany([{_id: 2}, {_id: 3}, {_id: 4}]) { "acknowledged" : true, "insertedIds" : [ 2, 3, 4 ] }
> // the old update API > db.test.update( ... {_id: 1}, ... {$set: {x: 1}}, ... true /* upsert */, ... false /* multi */ ) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
> // the new update API > db.test2.updateOne( ... {_id: 1}, ... {$set: {x: 1}}, ... {upsert: true} ) { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0, "upsertedId" : 1 }
> // the old replace API > db.test.update( ... {_id: 1}, ... {set: {x: 1}} // OOPS!! ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > // document was replaced > db.test.findOne() { "_id" : 1, "set" : { "x" : 1 } }
> // the old delete API > db.test.remove({}) // remove EVERYTHING!!
> // the new delete API > db.test2.deleteOne({}) { "acknowledged" : true, "deletedCount" : 1 } > db.test2.deleteMany({}) { "acknowledged" : true, "deletedCount" : 3 }
Read more on
https://www.mongodb.com/blog/post/consistent-crud-api-next-generation-mongodb-drivers
No comments:
Post a Comment