检查键是否存在于嵌套的子文档中
Check key exist in nested subdocument
我正在使用 MongoDB Java 驱动程序 3.2 并尝试检查嵌套子文档中是否存在字段。我不得不采取一些非常尴尬的方法。例如:
ObjectId oid = new ObjectId();
Document newDoc = new Document("_id", oid);
newDoc.append("c_doc", new Document("cid", "child document").append("co", "obj"));
String testKey = "c_doc.cid";
if (newDoc.containsKey(testKey)) {
System.out.println("exist");
} else {
System.out.println("not exist");
}
if (newDoc.get(testKey) != null) {
System.out.println("get exist");
} else {
System.out.println("get null");
}
if (((Document)newDoc.get("c_doc")).containsKey("cid")){
System.out.println("get and check: exist");
} else {
System.out.println("get and check: not exist");
}
前两种检查键cid是否存在于c_doc的子文档中的方法很直观但失败了。只有第三个有效,但很尴尬。我的真实数据还有一个子文档要进入。
我必须编写一个实用程序函数来执行此检查,但我认为它不应该这么难看。
Document
本质上是一个 Map
并且不支持像 testKey
这样的点分语法,所以你必须像你一样手动走下去。
我正在使用 MongoDB Java 驱动程序 3.2 并尝试检查嵌套子文档中是否存在字段。我不得不采取一些非常尴尬的方法。例如:
ObjectId oid = new ObjectId();
Document newDoc = new Document("_id", oid);
newDoc.append("c_doc", new Document("cid", "child document").append("co", "obj"));
String testKey = "c_doc.cid";
if (newDoc.containsKey(testKey)) {
System.out.println("exist");
} else {
System.out.println("not exist");
}
if (newDoc.get(testKey) != null) {
System.out.println("get exist");
} else {
System.out.println("get null");
}
if (((Document)newDoc.get("c_doc")).containsKey("cid")){
System.out.println("get and check: exist");
} else {
System.out.println("get and check: not exist");
}
前两种检查键cid是否存在于c_doc的子文档中的方法很直观但失败了。只有第三个有效,但很尴尬。我的真实数据还有一个子文档要进入。
我必须编写一个实用程序函数来执行此检查,但我认为它不应该这么难看。
Document
本质上是一个 Map
并且不支持像 testKey
这样的点分语法,所以你必须像你一样手动走下去。