从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[] ) { //创建一个MongoDB客户端 MongoClient mongo = new MongoClient( "localhost" , 27017 ); //连接到数据库 MongoDatabase database = mongo.getDatabase("myDatabase"); //创建一个收集对象 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"); //插入创建的文档 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"); //检索文件 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}}