Signup/Sign In

MongoDB with Java: Inserting Document

We will continue with our collection User for data insertion which we created after connecting with MongoDB database. Let us consider various scenarios for inserting data in our collection User.


Inserting Document into Collection with default _id

Suppose, we want to create a document in our User collection with fields name and description, we will make use of following code snippet:

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient; 
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			// get the User collection from DB
			DBCollection userCollection = db.getCollection("User");
			BasicDBObject bO = new BasicDBObject();

			bO.put("name", "XYZ");
			bO.put("description", "Data insertion in MongoDB");

			// inserting data into collection
			userCollection.insert(bO);
		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

In, the above code snippet, we used getCollection() method to get the existing collection User. Then an object of BasicDBObject is created and fields name and description are put in the object with values. The output generated can be seen using MongoDB Compass tool.


Data Insertion in MongoDB

As a result of executing the above code a new entry with name and description is created with a randomly generated _id value.


Inserting Document into Collection with custom _id

While creating document(inserting data) in any collection, mongoDB provides its own unique id referred as _id. If we want to provide our own custom id, we can provide it. Refer the below code snippet for the same.

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient; 
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			// get the User collection from DB
			DBCollection userCollection = db.getCollection("User");
			BasicDBObject bO = new BasicDBObject();

			// adding custom _id
			bO.put("_id", "xyz123");
			bO.put("name", "XYZ");
			bO.put("description", "Data insertion in MongoDB");

			// inserting data into collection
			userCollection.insert(bO);
		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

When the above program is executed, a new document is inserted in the collection with the values provided along with the provided value for _id field.

Data Insertion in MongoDB

In the output, we can find that document is created with our unique custom id: xyz123.