MongoDB嵌套文档搜索

时间:2010-12-13 20:53:40

标签: java mongodb

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

形式

userID:34343, 名称:Joe Bloggs

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

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

由于

2 个答案:

答案 0 :(得分:8)

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

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

因此,如果您需要找到发送用户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

另请查看java driver

的教程

答案 1 :(得分: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> } }一样。

相关问题