2010-12-13 249 views
1

如何通过mongodb文档搜索文档嵌套文档。例如,我收集了一些私人消息。每条私人消息都有两个嵌套文件 - 一个代表发送用户,另一个代表接收用途。两个嵌套文档的形式为 -MongoDB嵌套文档搜索

用户ID:34343, 名称:李四

我想是能够搜索用户发送的所有邮件(例如搜索发件人用户嵌套文件)。

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

感谢

回答

8

按照我的理解u有文档的结构是这样的:

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

所以如果你需要找到用户ID发送用户= 34345,你只需要做到以下(我只是觉得是这样的,因为其实我与蒙戈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 

还要检查教程java driver

+0

我知道这是旧的答案,但实际上我得到无效的运算符'$ eq' :-( – Betlista 2012-11-11 17:44:13

+2

试试这个'query.put(“sendingUser.userID”,34345);'。 – 2012-11-12 03:36:14

+0

是的,我发现后来感谢,我的问题是,我使用了几个数据库和'query.put(“sendingUser.userID”,34345);'返回'null',我认为它不工作,但记录不在数据库中,我的错误。它工作正常。 – Betlista 2012-11-12 10:09:54

0

适用于MongoDB Java驱动程序v3.2.2。你可以做这样的事情:

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

你可以把$eq的JSON风格的查询字符串内。像{ <field>: { $eq: <value> } }