限制Result中的字段
我正在使用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 usersCursor = col.find(query)
final BasicDBObject query = new BasicDBObject("{}", new BasicDBObject("_id", true)); final MongoCursor 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)
是否有可能这样做或者我必须获取所有字段?
问候
索伦
使用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));
看看DBCollection的实现find()
。 以下命令返回集合中具有"username"
, "firstname"
和"lastname"
字段的每个文档的"username"
, "firstname"
, "lastname"
和"_id"
"lastname"
字段:
BasicDBObject keys = new BasicDBObject(); keys.put("username", 1); keys.put("firstname", 1); keys.put("lastname", 1); final MongoCursor usersCursor = col.find(new BasicDBObject(), keys);
collection .find(new Document(...).append(...)) .projection(new Document(...).append(...))
这将为您提供FindIterable
,然后您可以像DBCursor
一样进行迭代。