我有一些看起来像这样的 mongo 数据
{
"_id": {
"$oid": "5984cfb276c912dd03c1b052"
},
"idkey": "123",
"objects": [{
"key1": "481334",
"key2": {
"key3":"val3",
"key4": "val4"
}
}]
}
我想知道它的价值key4
是什么。我还需要按idkey
和过滤结果key1
。所以我尝试了
doc = mongoCollection.find(and(eq("idKey", 123),eq("objects.key1", 481334))).first();
这有效。但我想检查 的值key4
而不必打开整个对象。是否有一些我可以执行的查询给我的值key4
?请注意,我可以更新key4
as
mongoCollection.updateOne(and(eq("idKey", 123), eq("objects.key1", 481334)),Updates.set("objects.$.key2.key4", "someVal"));
我是否可以运行类似的查询来获取的值key4
?
更新
非常感谢@dnickless 的帮助。我尝试了你的两个建议,但我得到了空值。这是我尝试过的
existingDoc = mongoCollection.find(and(eq("idkey", 123), eq("objects.key1", 481334))).first();
这给了我
Document{{_id=598b13ca324fb0717c509e2d, idkey="2323", objects=[Document{{key1="481334", key2=Document{{key3=val3, key4=val4}}}}]}}
到目前为止,一切都很好。接下来我尝试了
mongoCollection.updateOne(and(eq("idkey", "123"), eq("objects.key1", "481334")),Updates.set("objects.$.key2.key4", "newVal"));
现在我试图将更新的文档作为
updatedDoc = mongoCollection.find(and(eq("idkey", "123"),eq("objects.key1","481334"))).projection(Projections.fields(Projections.excludeId(), Projections.include("key4", "$objects.key2.key4"))).first();
为此我得到了
Document{{}}
最后我尝试了
updatedDoc = mongoCollection.aggregate(Arrays.asList(Aggregates.match(and(eq("idkey", "123"), eq("objects.key1", "481334"))),
Aggregates.unwind("$objects"), Aggregates.project(Projections.fields(Projections.excludeId(), Projections.computed("key4", "$objects.key2.key4")))))
.first();
为此我得到了
Document{{key4="newVal"}}
所以我很高兴:) 但是你能想出第一种方法不起作用的原因吗?
最终答案
感谢@dnickless 的更新
document = collection.find(and(eq("idkey", "123"), eq("objects.key1", "481334"))).projection(fields(excludeId(), include("key4", "objects.key2.key4"))).first();