MongoDB nested documents searching

后端 未结 2 1806
天命终不由人
天命终不由人 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: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

提交回复
热议问题