限制Result中的字段

Sör*_*ren 2 java mongodb mongodb-java

我正在使用MongoDB v3.0.1和MongoDB Java Driver 3.0.0-RC1.

我有一个用户集合,其中包含"username","firstname","lastname","email"等字段.

现在我想选择所有用户,但只选择"username","firstname"和"lastname"字段.

在Mongo-Shell上,它正在与之合作 db.user.find({}, { "username" : true , "firstname" : true , "lastname" : true})

但是我怎么能用Java做呢?我试过了 final BasicDBObject query = new BasicDBObject("{}", new BasicDBObject("_id", true)); final MongoCursor<Document> usersCursor = col.find(query)

为此,我得到一个空的结果,因为它被翻译为{ "{}" : { "_id" : true , "firstname" : true , "lastname" : true}}.

我也尝试过使用BasicDBList,但是不接受这个 col.find()

使用"旧"Mongo 2.x驱动程序 new BasicDBObject(BasicDBObject(), new BasicDBObject("username", true).append("firstname", true).append("lastname", true)

是否有可能这样做或者我是否必须获取所有字段?

问候
Sören

jye*_*min 5

使用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"));
Run Code Online (Sandbox Code Playgroud)

至于你说它在2.x驱动程序中工作的方式,这是不可能的,因为

new BasicDBObject(BasicDBObject(), BasicDBObject("username", true)
                                  .append("firstname", true)
                                  .append("lastname", true)
Run Code Online (Sandbox Code Playgroud)

不编译.我不确定你究竟用2.x做了什么,但是使用2.x中的DBCollection类(在3.0驱动程序中仍然支持)实现此目的的正确方法是:

    collection.find(new BasicDBObject(), new BasicDBObject("username", true)
                                        .append("lastname", true)
                                        .append("firstname", true));
Run Code Online (Sandbox Code Playgroud)