1

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", "marc@berger.com")).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" : "marc@berger.com", 
        "phone" : "12345"
    }, 
    {
        "firstname" : "Arnold", 
        "lastname" : "Schwarzenegger", 
        "email" : "pumping@iron.com", 
        "phone" : "12345"
    }]
}

I bassically want to get the document in users where the email is equal marc@berger.com, 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.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
marcmaann
  • 151
  • 1
  • 3
  • 12
  • 2
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) It's a commonly asked question and there are many possible solutions explained there. The basic ones in your case mean the use of the positional `$` operator in projection. – Blakes Seven Oct 01 '15 at 11:59
  • I think they are working with the `BasicDBObject` which are used if you use the '.getDB()' method but this method deprecated so I have to use '.getDatabase()' which returns a MongoDatabase. – marcmaann Oct 01 '15 at 12:16
  • The positional `$` 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. – Blakes Seven Oct 01 '15 at 12:19
  • Ok, I understand but i still don't know how to put the find command together. – marcmaann Oct 01 '15 at 12:39

1 Answers1

2

You use the positional $ operator in projection in order to return only the matched element of the array. This uses the .projection() method upon .find() with the MongoDB 3.x java driver:

MongoCursor<Document> f = coll.find(eq("users.email", "marc@berger.com"))
    .projection(new Document("users.$",1)).iterator();

Then all results will only return the matched array element rather than all array elements.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135