Home » Software Development » MongoDB » MongoDB insert example

About Nagendra Varma

BE graduate from Computer Science discipline. Quick learner and take in a zeal to learn new technologies. Broad experience in working on JavaEE applications in an agile environment with projects having critical deadlines. Expertise in developing WEB services.

MongoDB insert example

The article targets at explaining how to insert the documents into a MongoDB Collection.

The examples discussed in this article were developed and executed using MongoDB 3.2.6. And all these examples can be executed from the Mongo shell. Start the MongoDB instance by running ‘mongod’ process and then connect to this MongoDB instance using ‘mongo’ shell.

The following table gives an overview of the entire article:

 

1. Introduction

MongoDB provides standard library methods for any interaction. For inserting the documents into Collections, MongoDB provides following basic methods.

  1. db.collection.insertOne()
  2. db.collection.insertMany()
  3. db.collection.insert()

There are few other ways too insert the documents apart from the above said methods, but the article focuses on the above methods. So, let’s get into action and insert documents into a Collection.

All the examples in this article operates on a collection ‘posts’ which assumed to have the following schema:

{
  "title": "MongoDB insert example",
  "body": "Body of the post",
  "author": "Nagendra Varma",
  "date": "",
  "comments": [
    {
      "name": "Foo",
      "email": "foo@foo.org",
      "comment": "Good one"
    }
  ],
  "tags": ["MongoDB", "NoSQL"]
}

Although the MongoDB is schemaless, it is recommended that all the documents in a collection have similar structure.

All write(insert/update) operations in MongoDB are atomic at document level.

2. _id filed

MongoDB, if we don’t supply one, automatically adds an ‘_id’ field. Also, MongoDB automatically creates a unique primary index on _id field in every collection. MongoDB creates values for ‘_id’ field of type ObjectId, a value type defined in BSON spec. All ObjectId values are 12 bytes Hex string out of which first four bytes are seconds since the Unix epoch, next 3 bytes represent the Mac address of the machine on which the mongod server is running, next two bytes will represent the process ID and the last three bytes represents a random counter to ensure that all ObjectIds are unique even if a couple of writes happen under a set of conditions such that first 9 bytes leads to the same value.

If the document supplied to the insertXXX method has this field, it has be unique, or else it will throw an error and document will not be inserted.

3. Basic insert operations

For all the above basic insert methods, neither the database, nor the collection doesn’t have to exist, they will be created if they doesn’t exists when the first record has been inserted successfully in the first collection.

All the basic insert operations takes (a) document(s) as an argument and inserts it into the collection. The return value(s) of the basic insert method will also be a document indicating two things: one, that the write was acknowledged or not and the other, the unique identifier assigned to each of the document(s).

3.1. db.collection.insertOne()

insertOne() has been added to the Mongo shell from MongoDB 3.2.x. As the name implies, this method inserts a document given as an argument into a collection. Following is an example:

db.posts.insertOne({
  "title": "MongoDB insert example",
  "body": "Body of the post",
  "author": "Nagendra Varma",
  "date": "",
  "comments": [
    {
      "name": "Foo",
      "email": "foo@foo.org",
      "comment": "Good one"
    }
  ],
  "tags": [
    "MongoDB",
    "NoSQL"
  ]
})

This example results in a document being inserted in the posts collection(the collection will be created if it doesn’t exists already) and displays the following output:

{
	"acknowledged" : true,
	"insertedId" : ObjectId("575323e80dc8149bd88f1965")
}

3.2. db.collection.insertMany()

This method also has been introduced from 3.2.x. Inserts an array of documents into the collection, this can be used for batch inserts. Below gives an example of using insertMany:

db.posts.insertMany([
  {
    "title": "MongoDB insert example",
    "body": "Body of the post",
    "author": "Nagendra Varma",
    "date": "",
    "comments": [
      {
        "name": "Foo",
        "email": "foo@foo.org",
        "comment": "Good one"
      }
    ],
    "tags": [
      "MongoDB",
      "NoSQL"
    ]
  },
  {
    "title": "MongoDB show databases example",
    "body": "Body of the post",
    "author": "Nagendra Varma",
    "date": "",
    "comments": [
      {
        "name": "John",
        "email": "john@example.org",
        "comment": "Good one"
      }
    ],
    "tags": [
      "MongoDB",
      "NoSQL"
    ]
  },
  {
    "title": "MongoDB search example",
    "body": "Body of the post",
    "author": "Nagendra Varma",
    "date": "",
    "comments": [
      {
        "name": "Steve",
        "email": "steve@example.co.in",
        "comment": "Good one"
      }
    ],
    "tags": [
      "MongoDB",
      "NoSQL"
    ]
  }
])

The insertMany() outputs a document which has acknowledged flag and an array of ObjectId’s, one for each document given. The following is the output of the above statement.

{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("575328660dc8149bd88f1966"),
		ObjectId("575328660dc8149bd88f1967"),
		ObjectId("575328660dc8149bd88f1968")
	]
}

If any error occurs while inserting a document from the list of documents given, an error will be thrown and the operation halts. So, none of the documents after the faulty document will be inserted into the collection.

To get rid of this, we can pass one more document to the insertMany() method which contains only one field, namely ordered which is set to true by default. By setting ‘ordered’ to false, the documents will be inserted into the collection in an arbitrary fashion and only the faulty records will not be inserted and thrown as errors and displayed in the output.

3.3. db.collection.insert()

insert() can achieve the purpose of either of the above methods, it can insert a document or an array of documents into a collection.

The usage will be exactly the same as above examples, use insert instead of insertOne or insertMany.

4. db.collection.save()

Updates an existing document or inserts a new document, depending on its document parameter.

If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.

On the other hand, if the document contains an _id field, then the save() method is equivalent to an update with the upsert(insert the document if the document not found for the update) option set to true.

5. Conclusion

Thus, we have covered basic ways of inserting document(s) into MongoDB collections.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments