MongoDB - Insert Query

Now that we have a basic understanding of how to write and run queries in MongoDB, we can begin inserting some sample data so that we can talk to our database.

The db.collection.insert() method adds new documents into a collection.

Insert a Document into a Collection

Because we are not yet using PyMongo to interact with our database, we need to work with the MongoDB shell.

We want to add a new person to our people collection. If the collection does not already exist, MongoDB will create it for us automatically.

MongoDB shell version: 3.0.5  
connecting to: test  
> db.people.insert(
  {
  'name' : 'Craig Derington',
  'address' : {
    'streetnumber' : '1234',
    'streetname' : 'NW 10th Ave',
    'city' : 'Washington, D.C.',
    'state' : 'DC',
    'zip_code' : 20098
  },
  'contacts' : {
    'type' : 'email',
    'address' : 'this@domain.net',
    'active' : 1,
  },
  'role' : 'admin',
  'is_active' : 1,
  'date_created' : now(),
  });
WriteResult({'nInserted' : 1 })  

OK, our insert was successful. The MongoDB shells informs us that the write result operation resulted in 1 record being added to our people collection.

If the Write operation runs into an error, the WriteResult will contain the error details.

Now to double check our work, let's run a find() query on our newly inserted document.

MongoDB shell version: 3.0.5  
connecting to: test  
> db.people.find({ 'name' : 'Craig Derington' }).pretty();
{
  '_id' : ObjectId('560454d...'),
  'name' : 'Craig Derington',
  'address' : {
    'streetnumber' : '1234',
    'streetname' : 'NW 10th Ave',
    'city' : 'Washington, D.C.',
    'state' : 'DC',
    'zip_code' : 20098
  },
  'contacts' : {
    'type' : 'email',
    'address' : 'this@domain.net',
    'active' : 1,
  },
  'role' : 'admin',
  'is_active' : True,
}

And our result in exactly as we expected.

Create an Array of Documents

You can define a variable that references an array of embedded documents.

MongoDB shell version: 3.0.5  
connecting to: test  
> var myPersonList = [
    {
      'name' : 'Jimmy Crocket',
      'role' : 'user'
    },
    {
      'name' : 'Johnny Rocket',
      'role' : 'user'
    },
    {
      'name' : 'James Socket',
      'role' : 'moderator'
    },
];
db.people.insert( myPersonList );  
BulkWriteResult({  
  'writeErrors' : [],
  'writeConcernErrors' : [],
  'nInserted' : 3,
  'nUpserted' : 0,
  'nMatched' : 0,
  'nRemoved' : 0,
  'upserted' : []
  })

You'll notice here that instead of a WriteResult, we get a BulkInsertResult.

We can also get a bit more complex with the MongoDB insert statements and write some Javascript functions that loops over a list and creates many documents at once.

Again, run the MongoDB shell.

MongoDB shell version: 3.0.5  
connecting to: test  
> for (i=0; i < 1000; i++) { names=['Exam', 'Essay', 'Quiz']; for (j=0; j < 3; j++) { db.scores.insert( { 'student' : i, 'type' : names[j], 'score' : Math.round(Math.random() * 100) });}}
WriteResult( { 'nInserted' : 1 })  

Let's break down this statement into separate components.

First, we create an outer loop of 1000 students, in number format. Next, we create an inner loop with a list of score types, either exam, essay or quiz. Then, our MongoDB insert statement executes and inserts 3 random test scores for each score type for 1000 students.

We'll run some queries on these test scores in future posts.

In our next briefing, we will discuss MongoDB upserts. A unique feature of Non-Rel databases.

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus