christophmccann
christophmccann

Reputation: 4211

MongoDB nested documents searching

How do I search through mongodb documents where documents have nested documents. For example I have a collection of private messages. Each private message has two nested documents - one representing the sending user and the other representing the receiving use. Both nested documents have the form -

userID: 34343, name: Joe Bloggs

I would like to be able to search for all mail messages sent by a user (e.g. search the sender user nested document).

I am using the java driver. Do I need to create a DBObject which represents the nested document?

Thanks

Upvotes: 1

Views: 6202

Answers (2)

jpllosa
jpllosa

Reputation: 2202

For MongoDB Java Driver v3.2.2. You can do something like this:

FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.userID\": \"34343\"}"));
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.name\": \"Joe Bloggs\"}"));

You can put the $eq inside the JSON style query string. Like { <field>: { $eq: <value> } }.

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53675

As i understand u have document structure like this:

{
   "someProperty" : 1,
   "sendingUser" : {
               userID : 34343,
               name : "Joe Bloggs"
             },
   "recivingUser" : {
               userID : 34345,
               name : "Joe Bloggs"
             }
}

So if you need find sending user with userID = 34345 you just need do following(i just think that is so, because actually i am working with c# driver for mongo):

    DBCollection coll = db.getCollection("privateMessages")

    query = new BasicDBObject();

    query.put("sendingUser.userID", new BasicDBObject("$eq", 34345)); 

    cur = coll.find(query); // all documents with  sendingUser.userID = 34345 will be //returned by cursor

Also check tutorial for java driver

Upvotes: 8

Related Questions