MongoDB : Insert Document(s) in Collection Examples

The insert() Method:

The insert() method inserts one or more documents into a collection. Each document is provided as a parameter. The collection name is prepended to the insert() method.

MongoDB Example: Insert Multiple Documents in collection:

To insert multiple documents in collection, we define an array of documents and later we use the insert() method on the array variable as shown in the example below.

Here we are inserting three documents in the collection named “students”. This command will insert the data in “students” collection. For more info MongoDB Training

if the collection is not present then it will create the collection and insert these documents.

var beginners =
 [
    {
	"StudentId" : 1001,
	"StudentName" : "Steve",
        "age": 30
    },
    {
	"StudentId" : 1002,
	"StudentName" : "Negan",
        "age": 42
    },
    {
	"StudentId" : 3333,
	"StudentName" : "Rick",
        "age": 35
    },
];
db.students.insert(beginners);
Insert BasicDBObject in collection:

This one is simplest. Create an instance of BasicDBObject, populate data and call collection.insert() method. Learn practical skills from MongoDB Certification

BasicDBObject document = new BasicDBObject();
document.put("name", "lokesh");
document.put("website", "howtodoinjava.com");
 
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("addressLine1", "Sweet Home");
documentDetail.put("addressLine2", "Karol Bagh");
documentDetail.put("addressLine3", "New Delhi, India");
 
document.put("address", documentDetail);
 
collection.insert(document);
 
Output:
 
{ "_id" : { "$oid" : "538d56a3364192189d4f98fe"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3
Use DBObjectBuilder to insert document in collection:

Very similar to above example, only uses DBObjectBuilder to build DBObject.

BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
        .add("name", "lokesh")
        .add("website", "howtodoinjava.com");
  
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("addressLine1", "Some address")
.add("addressLine2", "Karol Bagh")
.add("addressLine3", "New Delhi, India");
 
documentBuilder.add("address", documentBuilderDetail.get());
 
collection.insert(documentBuilder.get());
 
Output:
 
{ "_id" : { "$oid" : "538d56a3364192189d4f98ff"} , "name" : "lokesh" , "website" : "howtodoinjava.com" , 
"address" : { "addressLine1" : "Sweet Home" , "addressLine2" : "Karol Bagh" , "addressLine3

To get in-depth knowledge, enroll for a live free demo on MongoDB Online Training

Leave a comment

Design a site like this with WordPress.com
Get started