Chapter 3. Creating, Updating, and Deleting Documents

This chapter covers the basics 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

Inserts 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"})

insertOne will add an "_id" key to the document (if you do not supply one) and store the document in MongoDB.

insertMany

If you need to insert multiple documents into a collection, you can use insertMany. This method enables you to pass an array of documents to the database. This is far more efficient because your code will not make a round trip to the database for each document inserted, but will insert them in bulk.

In the shell, you can try this out as follows:

> db.movies.drop()
true
> db.movies.insertMany([{"title" : "Ghostbusters"},
...                        {"title" : "E.T."},
...                        {"title" : "Blade Runner"}]);
{
      "acknowledged" : true,
       "insertedIds" : [
           ObjectId("572630ba11722fac4b6b4996"),
           ObjectId("572630ba11722fac4b6b4997"),
           ObjectId("572630ba11722fac4b6b4998")
       ]
}
> db.movies.find()
{ "_id" : ObjectId("572630ba11722fac4b6b4996"), "title" : "Ghostbusters" }
{ "_id" : ObjectId("572630ba11722fac4b6b4997"), "title" : "E.T." }
{ "_id" : ObjectId("572630ba11722fac4b6b4998"), "title" : "Blade ...

Get MongoDB: The Definitive Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.