无法使用键名称中的点访问MongoDB Java嵌套文档

在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作为键)应该可以,但不适用于我。

pf030232 回答:无法使用键名称中的点访问MongoDB Java嵌套文档

花一些时间阅读文档和其他Stack 溢出问题,我了解到在键名中使用点(例如 一键二键)应该可以,但是对我来说不是。

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。请注意,没有 no 密钥,名为one.two。键two在文档的子文档中的 中,键为one

因此,从您的代码中:

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

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

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

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

结果是“三”,符合预期。

,

MongoDB在字段名称中允许点。

document.get("one.two");

实际上会在寻找类似

的字段
data-id: "1234"
"one.two": "three"

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

本文链接:https://www.f2er.com/2469153.html

大家都在问