MongoDB nested documents searching

后端 未结 2 1807
天命终不由人
天命终不由人 2021-01-16 12:42

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 doc

相关标签:
2条回答
  • 2021-01-16 13:23

    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> } }.

    0 讨论(0)
  • 2021-01-16 13:27

    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

    0 讨论(0)
提交回复
热议问题