无法使用键名中的点访问 MongoDB Java 嵌套文档 [英] MongoDB Java nested documents not accessible using dots in key name
问题描述
在 Java 中使用 MongoDB API 时,我试图在如下所示的文档中检索 two
的值:
When using the MongoDB API in Java, I am trying to retrieve the value of two
in a document that looks like this:
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
表示键)应该可行,但它不适合我.
After spending some time reading documentation and other Stack Overflow questions, I learned that using dots in the key name (like one.two
for the key) should work, but it isn't for me.
推荐答案
在花了一些时间阅读文档和其他 Stack 之后溢出问题,我了解到在键名中使用点(比如one.two for the key) 应该有效,但不适合我.
After spending some time reading documentation and other Stack Overflow questions, I learned that using dots in the key name (like one.two for the key) should work, but it isn't for me.
点符号在 find
方法的查询过滤器中使用时效果很好.例如,
The dot-notation works fine when used within a find
method's query filter. For example,
Document document = collection.find(Filters.eq("one.two", "three")).first();
System.out.println(document); // prints the returned document
或其 mongo
shell 等价物:
or its mongo
shell equivalent:
db.collection.find( { "one.two": "three" } )
Document 类的get()
方法接受一个 Object
(一个 String 键)作为参数并返回一个 Object
.
The Document class's get()
method takes an Object
(a String key) as a parameter and returns an 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
.
The output Document{{_id=1.0, data-id=1234, one=Document{{two=three}}}}
shows there are three keys: _id
, data-id
and one
. Note there is no key named as one.two
. The key two
is within the sub-dcument of the document with the key one
.
所以,从你的代码:
document.get("one.two"); // This is null ((Document)
document.get("one")).get("two"); // Not null
第一条语句返回null
,下一条返回three
(字符串值).两者都是正确结果,这就是 Document
类 API 的行为.
The first statement returns null
, and the next one returns three
(the String value). Both are correct results and that is the behavior of the Document
class API.
您应该使用getEmbedded
方法来访问嵌入字段one.two
.因此,将 document.get("one.two")
替换为
You should use the method getEmbedded
to access the embedded field one.two
. So, replace document.get("one.two")
with
document.getEmbedded(Arrays.asList("one", "two"), String.class)
正如预期的那样,结果是三".
The result is "three", as expected.
这篇关于无法使用键名中的点访问 MongoDB Java 嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!