对于 3.0.0 Java 驱动程序中的新 CRUD API,正确的方法是使用与 MongoCollection.find() 链接的投影方法。由于投影方法采用 Bson 接口的实例,因此您可以使用许多不同的类来指定投影:
// using BasicDBObject
collection.find().projection(new BasicDBObject("username", true)
.append("lastname", true)
.append("firstname", true))
// using the new Document class
collection.find().projection(new Document("username", true)
.append("lastname", true)
.append("firstname", true));
// Using the new Projections builder
collection.find().projection(Projections.include("username", "lastname", "firstname"));
至于你说的在 2.x 驱动程序中的工作方式,这是不可能的,因为
new BasicDBObject(BasicDBObject(), BasicDBObject("username", true)
.append("firstname", true)
.append("lastname", true)
不编译。我不确定您在 2.x 中到底做了什么,但使用 2.x 中的 DBCollection 类(在 3.0 驱动程序中仍然受支持)完成此操作的正确方法是:
collection.find(new BasicDBObject(), new BasicDBObject("username", true)
.append("lastname", true)
.append("firstname", true));