MongoDB嵌套文档搜索

chr*_*ann 1 java mongodb

如何搜索文档具有嵌套文档的mongodb文档.例如,我有一组私人消息.每条私人消息都有两个嵌套文档 - 一个代表发送用户,另一个代表接收用户.两个嵌套文档都有以下形式 -

userID:34343,name:Joe Bloggs

我希望能够搜索用户发送的所有邮件消息(例如,搜索发件人用户嵌套文档).

我正在使用java驱动程序.我是否需要创建一个代表嵌套文档的DBObject?

谢谢

And*_*ich 8

据我所知你有这样的文档结构:

{
   "someProperty" : 1,
   "sendingUser" : {
               userID : 34343,
               name : "Joe Bloggs"
             },
   "recivingUser" : {
               userID : 34345,
               name : "Joe Bloggs"
             }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您需要找到发送用户ID = 34345的用户,您只需要执行以下操作(我只是认为是这样,因为实际上我正在使用mongo的c#驱动程序):

    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
Run Code Online (Sandbox Code Playgroud)

另请查看java驱动程序的教程

  • 试试这个`query.put("sendingUser.userID",34345);`. (2认同)