【问题标题】:MongoDB Java nested documents not accessible using dots in key name使用键名中的点无法访问 MongoDB Java 嵌套文档
【发布时间】:2020-04-10 16:05:26
【问题描述】:

在 Java 中使用 MongoDB API 时,我试图在如下所示的文档中检索 two 的值:

data-id: "1234"
one:
    two: "three"

我正在运行这个:

MongoCollection<Document> documents = ...;
Document document = documents.find(Filters.eq("data-id", "1234")).first(); // Not null
document.get("one"); // Not null
document.get("one.two"); // This is null
((Document) document.get("one")).get("two"); // Not null

在花了一些时间阅读文档和其他 Stack Overflow 问题后,我了解到在键名中使用点(例如 one.two 表示键)应该可以,但它不适合我。

【问题讨论】:

    标签: java mongodb mongodb-java


    【解决方案1】:

    在花了一些时间阅读文档和其他堆栈之后 溢出问题,我了解到在键名中使用点(例如 one.two 作为键)应该可以工作,但它不适合我。

    点符号在find 方法的查询过滤器中使用时效果很好。例如,

    Document document = collection.find(Filters.eq("one.two", "three")).first();
    System.out.println(document);    // prints the returned document
    

    或其mongo shell 等效项:

    db.collection.find( { "one.two": "three" } )
    


    Document 类的get() 方法将Object(字符串键)作为参数并返回Object

    考虑代码:

    Document doc = coll.find(eq("data-id", "1234")).first();
    System.out.println(doc);
    

    输出Document{{_id=1.0, data-id=1234, one=Document{{two=three}}}} 显示有三个键:_iddata-idone。请注意,有一个名为one.twono 键。键 two 位于文档的子文档中,键为 one

    所以,从你的代码:

    document.get("one.two");    // This is null ((Document)
    document.get("one")).get("two"); // Not null
    

    第一条语句返回null,下一条语句返回three(字符串值)。两者都是正确的结果,这就是Documentclass API 的行为。

    您应该使用方法getEmbedded 来访问嵌入字段one.two。因此,将document.get("one.two") 替换为

    document.getEmbedded(Arrays.asList("one", "two"), String.class)
    

    正如预期的那样,结果是“三”。

    【讨论】:

      【解决方案2】:

      MongoDB 允许在字段名称中使用点。

      document.get("one.two");
      

      实际上会寻找类似的字段

      data-id: "1234"
      "one.two": "three"
      

      其中“one.two”是一个简单字段,而不是嵌入文档。

      【讨论】:

      • MongoDB 不能有带点的键...但我明白你的意思。
      • 实际上,从 3.6 版本开始,它确实允许在字段名称中使用点。见Restrictions on Field Names
      猜你喜欢
      • 2018-09-19
      • 2021-08-28
      • 2018-07-26
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多