Restrict fields in Result

放肆的年华 提交于 2019-12-06 05:29:59

With the new CRUD API in the 3.0.0 Java driver, the proper way to do it is with the projection method that is chained off off MongoCollection.find(). Since the projection method takes an instance of the Bson interface, there are a number of different classes you can use to specify the projection:

    // 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"));

As for the way you say it works in the 2.x driver, that's not possible, as

new BasicDBObject(BasicDBObject(), BasicDBObject("username", true)
                                  .append("firstname", true)
                                  .append("lastname", true)

does not compile. I'm not sure what exactly you were doing with 2.x, but the proper way to accomplish this with the DBCollection class in 2.x (which is still supported in the 3.0 driver), is:

    collection.find(new BasicDBObject(), new BasicDBObject("username", true)
                                        .append("lastname", true)
                                        .append("firstname", true));

Have a look at the implementation of DBCollection find(). The following returns the "username", "firstname", "lastname" and "_id" fields for every document in the collection that has an "username", "firstname" and "lastname" fields:

BasicDBObject keys = new BasicDBObject();
keys.put("username", 1);
keys.put("firstname", 1);
keys.put("lastname", 1);
final MongoCursor<Document> usersCursor = col.find(new BasicDBObject(), keys);

collection .find(new Document(...).append(...)) .projection(new Document(...).append(...))

This will give you a FindIterable and then you can iterate through as you would DBCursor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!