My question is similar to this one but I am using Java Driver.
This is a document from my collection:
{
"_id": "7",
"servers": [
{
"ip_port": "127.0.0.1:8081",
"name": "server1"
},
{
"ip_port": "127.0.0.1:8082",
"name": "server2"
}
]
}
After the query I want to get a document like this:
{
"ip_port": "127.0.0.1:8081"
}
I have tried to translate the instructions of the second answer of the linked question in Java and the result was this:
MongoCursor<Document> cursor = db.getCollection("collection")
.find(and(eq("_id", "7"),
eq("servers.name", "server1")))
.projection(Projections.fields(Projections.elemMatch("servers"), Projections.excludeId()))
.iterator();
but if I execute this query and I print cursor.next().toJson()
this is what I get:
{ "server" : [{ "ip_port" : "127.0.0.1:8081", "name" : "server1" }] }
So how can I get a specific embedded document inside Mongo DB with Java Driver?