Today we will look into MongoDB insert commands. Mongo Client can be used to insert a document into a collection. We can also insert an array of documents, today we will look into various operations related to MongoDB insert.
MongoDB insert
For MongoDB insert example, I am using MongoDB version 3.4.7 and java driver version 3.5.0. However these should work with other versions too. Note that mongo java driver API has totally changed in 3.x version, so if you are using older 2.x version then you will have to modify the code accordingly.
MongoDB insert using Mongo Client
Here is a simple example where I am inserting a single document into Person collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
pankaj:mongodb pankaj$ mongo MongoDB shell version v3.4.7 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.7 Welcome to the MongoDB shell. For interactive help, type "help". > use journaldev switched to db journaldev > show collections > db.Persons.insert({name:"Pankaj",country:"India"}) WriteResult({ "nInserted" : 1 }) > show collections Persons > db.Persons.find() { "_id" : ObjectId("59a3d6bf03ca62436260d57a"), "name" : "Pankaj", "country" : "India" } ></code>Notice that if we don’t provide primary key i.e <code style="text-align: justify; font-size: 16px;">_id</code><span style="text-align: justify; background-color: #ffffff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; font-size: 16px;"> key, MongoDB automatically generates it and it gets stored as </span><code style="text-align: justify; font-size: 16px;">ObjectId</code><span style="text-align: justify; background-color: #ffffff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; font-size: 16px;"> object.</span> |
Also check that it’s returning WriteResult
object containing the number of documents inserted. If the collection doesn’t exists, MongoDB will create it.
MongoDB insert with primary key
Now let’s provide primary key to the mongodb document and see different scenarios that can occur.
MongoDB insert single document with id
1 2 3 4 5 6 7 8 |
> db.Persons.insert({_id:123,name:"Pankaj",country:"India"}) WriteResult({ "nInserted" : 1 }) > db.Persons.find() { "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" } { "_id" : 123, "name" : "Pankaj", "country" : "India" } > |
What if there is already an object stored with the provided id.
MongoDB insert document duplicate key error
1 2 3 4 5 6 7 8 9 10 11 |
> db.Persons.insert({_id:123,name:"David",country:"India"}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 123.0 }" } }) > |
Well, from the output it seems that WriteResult also provide error code and message associated with it, notice that rows inserted is returned as 0.
MongoDB bulk insert
Now let’s try the insert multiple documents with a single command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
> db.Persons.insert([{name:"David"},{name:"Kumar"}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > |
So with an array of documents, MongoDB insert operation returns BulkWriteResult
that contains more information.
Let’s try to insert array of documents with id also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
> db.Persons.insert([{_id:100,name:"David"},{_id:101,name:"Kumar"}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > |
Now let’s see what happens when there is an error in inserting one of the documents in the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
> db.Persons.insert( ... [{_id:102,name:"PK"}, ... {_id:101,name:"Kumar"}, ... {_id:103,name:"PK"}]) BulkWriteResult({ "writeErrors" : [ { "index" : 1, "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 101.0 }", "op" : { "_id" : 101, "name" : "Kumar" } } ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.find() { "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" } { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : ObjectId("53fc40d1b1e38e3716f79114"), "name" : "David" } { "_id" : ObjectId("53fc40d1b1e38e3716f79115"), "name" : "Kumar" } { "_id" : 100, "name" : "David" } { "_id" : 101, "name" : "Kumar" } { "_id" : 102, "name" : "PK" } > |
It’s clear that operation is terminated when any of the document insertion fails, any further records are not inserted and we get error message clearly showing which of the record caused the issue.
MongoDB bulk insert ordered and writeConcern parameters
What if we are executing a bulk operation and want to process error documents later on, we can use ordered
parameter to tell MongoDB to skip the error document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
> db.Persons.insert( [{_id:102,name:"PK"}, {_id:101,name:"Kumar"}, {_id:103,name:"PK"}] ,{ordered:false}) BulkWriteResult({ "writeErrors" : [ { "index" : 0, "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 102.0 }", "op" : { "_id" : 102, "name" : "PK" } }, { "index" : 1, "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 101.0 }", "op" : { "_id" : 101, "name" : "Kumar" } } ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.find() { "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" } { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : ObjectId("53fc40d1b1e38e3716f79114"), "name" : "David" } { "_id" : ObjectId("53fc40d1b1e38e3716f79115"), "name" : "Kumar" } { "_id" : 100, "name" : "David" } { "_id" : 101, "name" : "Kumar" } { "_id" : 102, "name" : "PK" } { "_id" : 103, "name" : "PK" } > |
Similarly we can also pass writeConcern
parameter for different levels of concerns, default write concern is Acknowledged. We will look into it in future post.
MongoDB insert Java Example
Now let’s see different ways to use Java Driver to perform insert operations in MongoDB collection. Note that these java programs are using mongo-java-driver
version 3.5.0
.
-
-
MongoDB insert single document example
-
A simple program inserting a single document using MongoCollection.insertOne
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBInsertExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); MongoDatabase db = mongo.getDatabase("journaldev"); MongoCollection<Document> col = db.getCollection("Persons"); Document document = new Document(); document.append("name", "Pankaj"); document.append("country", "USA"); col.insertOne(document); System.out.println("ID Generated=" + document.getObjectId("_id").toString()); mongo.close(); } } |
Below image shows the output produced, notice the generated id being printed to console.
We can also pass our own id parameter like below.
1 2 3 4 |
document.append("_id",new ObjectId("123456789012".getBytes())); //min byte array length should be 12 document.append("_id", new ObjectId(new Date())); // ObjectId constructor also takes Date as argument |
However if we are trying to create instance of ObjectId by passing some parameter, such as document.append("_id",new ObjectId("1234"));
, it will throw below exception.
1 2 3 4 5 6 |
Exception in thread "main" java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [1234] at org.bson.types.ObjectId.parseHexString(ObjectId.java:549) at org.bson.types.ObjectId.<init>(ObjectId.java:239) at com.journaldev.mongodb.main.MongoDBInsertExample.main(MongoDBInsertExample.java:24) |
It’s because some validations are in place when argument is passed for ObjectId, the passed String should be a hexadecimal string. You can check it’s source code for more details.
If you try to pass ObjectId like document.append("_id", new ObjectId("1234".getBytes()));
, it will throw following exception.
1 2 3 4 5 6 7 |
Exception in thread "main" java.lang.IllegalArgumentException: state should be: buffer.remaining() >=12 at org.bson.assertions.Assertions.isTrueArgument(Assertions.java:62) at org.bson.types.ObjectId.<init>(ObjectId.java:272) at org.bson.types.ObjectId.<init>(ObjectId.java:249) at com.journaldev.mongodb.main.MongoDBInsertExample.main(MongoDBInsertExample.java:33) |
The reason is that byte array minimum size should be 12.
-
-
MongoDB insert Map java program
-
If you look at Document
example above, you will find it’s very similar to Map. We can insert a Map easily as a document, sample code snippet is given below.
1 2 3 4 5 6 7 8 |
Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("name", "Pankaj"); dataMap.put("country", "USA"); dataMap.put("_id",new ObjectId("123459789012".getBytes())); Document document = new Document(dataMap); col.insertOne(document); |
-
-
MongoDB insert JSON Document
-
Sometimes we get JSON response, mostly when we are invoking web services. That’s why MongoDB provides an easy way to insert JSON document in MongoDB collection, as shown in below example.
1 2 3 4 5 |
String json = "{ 'name' : 'Pankaj', 'country' : 'USA' }"; Document document = Document.parse(json); col.insertOne(document); |
-
-
Inserting multiple documents
-
We can insert multiple documents too using Mongo java driver, a simple example is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.journaldev.mongodb.main; import java.util.ArrayList; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBInsertMultipleExample { public static void main(String[] args) { MongoClient mongo = new MongoClient("localhost", 27017); MongoDatabase db = mongo.getDatabase("journaldev"); MongoCollection<Document> col = db.getCollection("Persons"); List<Document> docs = new ArrayList<>(); docs.add(new Document("name", "Pankaj")); docs.add(new Document().append("name", "David")); col.insertMany(docs); for(Document doc : docs) { System.out.println("Name="+doc.getString("name")+", ID="+doc.getObjectId("_id").toString()); } mongo.close(); } } |
Output produced will be something like below.
1 2 3 4 |
Name=Pankaj, ID=59a404c9c5130d39760a01a2 Name=David, ID=59a404c9c5130d39760a01a3 |
That’s all for MongoDB insert example, we will look into more MongoDB features in coming posts.