I am working with MongoDB v3.0.1 and the MongoDB Java Driver 3.0.0-RC1.
I have an user collection with fields like "username", "firstname", "lastname", "email", and so on.
Now I want to select all users but only with the fields "username", "firstname" and "lastname".
On the Mongo-Shell it is working with db.user.find({}, { "username" : true , "firstname" : true , "lastname" : true})
But how can I do it in Java? I tried it with
final BasicDBObject query = new BasicDBObject("{}", new BasicDBObject("_id", true));
final MongoCursor<Document> usersCursor = col.find(query)
For this I get an empty result back because it's translated as { "{}" : { "_id" : true , "firstname" : true , "lastname" : true}}
.
I also tried it with BasicDBList, but this isn't accepted by col.find()
With the "old" Mongo 2.x driver I would use new BasicDBObject(BasicDBObject(), new BasicDBObject("username", true).append("firstname", true).append("lastname", true)
Is there a possibility to do that or do I have to fetch all fields?
Greetings
Sören
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
.
来源:https://stackoverflow.com/questions/29332266/restrict-fields-in-result