英文:
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"
}
}
}
}
但是我只需要节点 a.b.c.d
,我知道在读取整个JSON后可以在Java中处理它。但我的目的是仅读取所需部分。
期望的输出为:
{
"a": {
"b": {
"c": {
"d": "value1"
}
}
}
}
另请注意,我将保存具有随机结构的JSON,因此没有与之关联的POJO。如果有人可以为我提供指导,那将非常有帮助。
英文:
I'm trying to read a single JSON node from MongoDb via my Springboot project.
here is the sample JSON saved in Mongo:
"a": {
"b": {
"c": {
"d": "value1",
"e": "value2"
}
}
}
I tried:
public String get() {
BasicDBObject query = BasicDBObject.parse("{\"a.b.c.d\": \"value1\"}");
FindIterable<Document> dumps = mongoOperations.getCollection("data").find(query);
return dumps.first().toJson();
}
response I got:
{
"_id": {
"$oid": "5e8aa42602ef9f05bf35ff59"
},
"a": {
"b": {
"c": {
"d": "value1",
"e": "value2"
}
}
}
}
but I only need the node a.b.c.d, I know I can do it in java after reading the whole JSON. But my intention is to read only the needed part.
Expected Output:
{
"a": {
"b": {
"c": {
"d": "value1"
}
}
}
}
Also please note that I'll be saving JSONs with random schema so no POJOs associated with it. It would be really helpful if somebody can guide me on this.
答案1
得分: 1
你可以使用 find
查询中的 _projection_
来仅获取指定的字段。在尝试了 MongoDB Spring Data 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()));
输出结果:
{"a": {"b": {"c": {"d": "value1"}}}}
英文:
You can get the specified field only, using a projection with the find
query. Tried with MongoDB Spring Data 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()));
The output:
{"a": {"b": {"c": {"d": "value1"}}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论