花一些时间阅读文档和其他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}}}}
显示有三个键:_id
,data-id
和one
。请注意,没有 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