Explain Java MongoDB projections

JavaObject Oriented ProgrammingProgramming

While retrieving data from MongoDb collections you can select only necessary data using projections. In Java, you can project necessary data while reading the documents from a collection using the projection() method. Invoke this method on the result of find(), bypassing the names of the required filed names as −

projection(Projections.include("name", "age"));

Example

Following Java examples read the documents from a collection, using projection we are displaying the values of name and age fields only.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
public class ProjectionExample {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection object
      MongoCollection<Document>collection = database.getCollection("students");
      Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
      Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
      Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");
      //Inserting the created documents
      List<Document> list = new ArrayList<Document>();
      list.add(document1);
      list.add(document2);
      list.add(document3);
      collection.insertMany(list);
      System.out.println("Documents Inserted");
      collection = database.getCollection("students");
      //Retrieving the documents
      FindIterable<Document> iterDoc =
      collection.find().projection(Projections.include("name", "age"));
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
   }
}

Output

Documents Inserted
Document{{_id=5e8966533f68506911c946dc, name=Ram, age=26}}
Document{{_id=5e8966533f68506911c946dd, name=Robert, age=27}}
Document{{_id=5e8966533f68506911c946de, name=Rhim, age=30}}
raja
Published on 10-Apr-2020 10:46:22
Advertisements