Hello I am using MONGODB java driver version 4.5.1, I created a method to query a document and grab a specific field.
(id is a discord id not document _id)
final MONGODB mongodb = new MONGODB();
public ArrayList<Document> getRoom(long id) {
ArrayList<Document> results = mongodb.collection.find(
new Document("id",id)
).projection(
new Document("room",1)
).into(new ArrayList<>());
System.out.println(results.size());
for (Document result : results) {
System.out.println(result);
}
return results;
}
this returns
Document{{_id=6276ed329a9a491cc223ae32, room=pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl}}
I am looking to improve this to only have it return the contents of room=, and not the _id field
2
Answers
I improved it by adding
.append("id",0)
to the projectionthis now returns what I need
Document{{room=pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl}}
The term for this is projection, you can have a look at: https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/
As the documentation suggests;