解释 Java MongoDB 投影


从 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}}

更新于: 10-4-2020

1K+ 浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告