MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java - Inserting a Document



MongoDB provides MongoCollection class to insert a document in a collection.

Syntax

// Select a collection
MongoCollection<Document> collection =  database.getCollection("sampleCollection");

// Create a Document
Document document = new Document("title", "MongoDB");

// Insert the Document
collection.insertOne(document);

Inserting a Document in a Collection

To insert a document, we first need to connect to a database and then select the collection and then insert the document as shown below −

package com.tutorialspoint.mongodb;

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;  

public class MongoDBTester { 
   
   public static void main( String args[] ) { 

      String uri = "mongodb://localhost:27017/";

      try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("myDb");

         System.out.println("Connected to the database successfully");
         // Selecting a collection 
         MongoCollection<Document> collection =  database.getCollection("sampleCollection"); 
         System.out.println("Collection selected successfully"); 
		 
         Document document = new Document("title", "MongoDB")
            .append("description", "database")
            .append("likes", 100)
            .append("url", "http://www.tutorialspoint.com/mongodb/")
            .append("by", "tutorials point");

         // Inserting document into the collection
         collection.insertOne(document);
         System.out.println("Document inserted successfully");
      }
   } 
}

Output

Now, let's compile and run the above program to insert a document in a collection in our database myDb.

On executing, the above program gives you the following output.

Connected to the database successfully
Collection selected successfully
Document inserted successfully
Advertisements