Here's my code
ServerAddress sa = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(sa);
MongoDatabase db = mongoClient.getDatabase("waitinglist");
MongoCollection<Document> coll = db.getCollection("users");
MongoCursor<Document> f = coll.find(eq("users.email", "[email protected]")).iterator();
try {
while (f.hasNext()) {
System.out.println("Mongo Cursor: " +f.next().toJson());
}
} finally {
f.close();
}
And here is how my collection looks:
{
"_id" : ObjectId("560b8b76a37991ab2d650ca9"),
"users" : [
{
"firstname" : "Marc",
"lastname" : "Berger",
"email" : "[email protected]",
"phone" : "12345"
},
{
"firstname" : "Arnold",
"lastname" : "Schwarzenegger",
"email" : "[email protected]",
"phone" : "12345"
}]
}
I bassically want to get the document in users where the email is equal [email protected], but it returns the whole document with the array as one. I think the problem is the first parameter in the eq method but I can't find a solution on google how make that statement.
$operator in projection.BasicDBObjectwhich are used if you use the '.getDB()' method but this method deprecated so I have to use '.getDatabase()' which returns a MongoDatabase.$operator has nothing to do with anything deprecated as it's a basic construct. In projection this tells MongoDB to only return the first matched element of the array. Other solutions there have multiple uses of aggregate to return "multiple" matches. Look for using "projection" of fields in your query. The solutions scale over all languages and drivers as it's just the basic way this is done with MongoDB.