Another common task when interacting with MongoDB databases is inserting documents into collections. To insert a document, you need to first create a JavaScript object that represents the document you want to store. You create a JavaScript object because the BSON format that MongoDB uses is based on JavaScript notation.
Once you have a JavaScript version of your new document, you can store it in the MongoDB database by using the insert()
method on an instance of the Collection
object that is connected to the database. The following is the syntax for the insert()
method:
insert(docs, [options], callback)
The docs
parameter can be a single document object or an array of document objects. The options
parameter specifies the database change options described in Table 14.1. The callback
parameter is required if you are implementing a write concern in options
. The first parameter of callback
is an error, and the second parameter is an array of the documents inserted into the collection.
Listing 14.1 is a basic example of inserting documents. Lines 2–9 show a function that accepts the Collection
object and an object to insert. The insert()
method is called, and the resulting array of inserted objects (one at a time in this case) is displayed on the console, as shown in Figure 14.1. Lines 10–13 open the connection to the MongoDB server, clear out the nebulae
collection, and then re-create it to provide a clean slate. Then lines 14–19 call addObject()
for a series of JavaScript objects describing nebulae.
01 var MongoClient = require('mongodb').MongoClient;
02 function addObject(collection, object){
03 collection.insert(object, function(err, result){
04 if(!err){
05 console.log("Inserted : ");
06 console.log(result);
07 }
08 });
09 }
10 MongoClient.connect("mongodb://localhost/", function(err, db) {
11 var myDB = db.db("astro");
12 myDB.dropCollection("nebulae");
13 myDB.createCollection("nebulae", function(err, nebulae){
14 addObject(nebulae, {ngc:"NGC 7293", name:"Helix",
15 type:"planetary",location:"Aquila"});
16 addObject(nebulae, {ngc:"NGC 6543", name:"Cat's Eye",
17 type:"planetary",location:"Draco"});
18 addObject(nebulae, {ngc:"NGC 1952", name: "Crab",
19 type:"supernova",location:"Taurus"});
20 });
21 setTimeout(function(){ db.close(); }, 3000);
22 });