'Return only results of specific field - Mongodb java
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
Solution 1:[1]
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;
You can remove the _id field from the results by setting it to 0 in the projection, as in the following example:
findIterable = collection.find(eq("status", "A"))
.projection(fields(include("item", "status"), excludeId()))
Solution 2:[2]
I improved it by adding
.append("id",0) to the projection
public ArrayList<Document> getRoom(long id) {
ArrayList<Document> results = mongodb.collection.find(
new Document("id",id)
).projection(
new Document("room",1).append("_id",0)
).into(new ArrayList<>());
System.out.println(results.size());
for (Document result : results) {
System.out.println(result);
}
return results;
}
this 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}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Can Arda Aydin |
| Solution 2 | Vincent Banks |
