![](/img/trans.png)
[英]How to delete object from list in JSON using SpringBoot and MongoDB
[英]How to read only a particular JSON node from MongoDb in SpringBoot
我正在尝试通过我的 Springboot 项目从 MongoDb 读取单个 JSON 节点。
这是保存在 Mongo 中的示例 JSON:
"a": {
"b": {
"c": {
"d": "value1",
"e": "value2"
}
}
}
我试过了:
public String get() {
BasicDBObject query = BasicDBObject.parse("{\"a.b.c.d\": \"value1\"}");
FindIterable<Document> dumps = mongoOperations.getCollection("data").find(query);
return dumps.first().toJson();
}
我得到的回应:
{
"_id": {
"$oid": "5e8aa42602ef9f05bf35ff59"
},
"a": {
"b": {
"c": {
"d": "value1",
"e": "value2"
}
}
}
}
但是我只需要节点abc.d,我知道在阅读了整个JSON之后我可以在java中做到这一点。 但我的意图是只阅读需要的部分。
预期 Output:
{
"a": {
"b": {
"c": {
"d": "value1"
}
}
}
}
另请注意,我将使用随机模式保存 JSON,因此没有与之关联的 POJO。 如果有人可以指导我这将非常有帮助。
您只能使用带有find
查询的投影来获取指定的字段。 尝试使用 MongoDB Spring 数据 2.2.6:
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
Query qry = new Query();
qry.fields().include("a.b.c.d").exclude("_id");
List<Document> list = mongoOps.find(qry, Document.class, "collection");
list.forEach(doc -> System.out.println(doc.toJson()));
output:
{"a": {"b": {"c": {"d": "value1"}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.