【问题标题】:MongoDB nested documents searchingMongoDB 嵌套文档搜索
【发布时间】:2011-05-24 22:05:53
【问题描述】:

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

用户 ID:34343, 名称:乔博客

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

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

谢谢

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    据我了解,您的文档结构如下:

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

    因此,如果您需要查找 userID = 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的教程

    【讨论】:

    • 我知道这是较旧的答案,但实际上我得到了无效的运算符 $eq :-(
    • 试试这个query.put("sendingUser.userID", 34345);
    • 是的,后来我发现,谢谢,我的问题是我使用了几个数据库,query.put("sendingUser.userID", 34345); 返回了null,我认为它不起作用,但记录不在数据库中,我的错误。它工作正常。
    【解决方案2】:

    适用于 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 样式的查询字符串中。喜欢{ &lt;field&gt;: { $eq: &lt;value&gt; } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多