Chapter 3. Creating, Updating, and Deleting Documents

This chapter covers the basics of moving data in 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 and Saving Documents

Inserts are the basic method for adding data to MongoDB. To insert a document into a collection, use the collection’s insert method:

> db.foo.insert({"bar" : "baz"})

This will add an "_id" key to the document (if one does not already exist) and store it in MongoDB.

Bulk Insert

If you have a situation where you are inserting multiple documents into a collection, you can make the insert faster by using batch inserts. Batch inserts allow you to pass an array of documents to the database.

In the shell, you can try this out using the batchInsert function, which is similar to insert except that it takes an array of documents to insert:

> db.foo.insert([{"_id" : 0}, {"_id" : 1}, {"_id" : 2}])
> db.foo.find()
{ "_id" : 0 }
{ "_id" : 1 }
{ "_id" : 2 }

Sending dozens, hundreds, or even thousands of documents at a time can make inserts significantly faster.

Batch inserts are only useful if you are inserting multiple documents into a single collection: you cannot use batch inserts to insert into multiple collections with a single request. If you are just importing raw data (for example, from a data feed or MySQL), there are command-line tools like ...

Get MongoDB: The Definitive Guide, 2nd 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.