MongoDb 컬렉션에서 데이터를 검색하는 동안 프로젝션을 사용하여 필요한 데이터만 선택할 수 있습니다. Java에서는 projection()을 사용하여 컬렉션에서 문서를 읽는 동안 필요한 데이터를 투영할 수 있습니다. 방법. find()의 결과에 대해 이 메서드를 호출하고 필요한 필드 이름의 이름을 -
로 무시합니다.projection(Projections.include("name", "age")); 예시
다음 Java 예제는 컬렉션에서 문서를 읽고 프로젝션을 사용하여 name 및 age 필드의 값만 표시합니다.
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());
}
}
} 출력
Documents Inserted
Document{{_id=5e8966533f68506911c946dc, name=Ram, age=26}}
Document{{_id=5e8966533f68506911c946dd, name=Robert, age=27}}
Document{{_id=5e8966533f68506911c946de, name=Rhim, age=30}}