如何在 Spring Boot 中从 MongoDb 中仅读取特定的 JSON 节点

Posted

技术标签:

【中文标题】如何在 Spring Boot 中从 MongoDb 中仅读取特定的 JSON 节点【英文标题】:How to read only a particular JSON node from MongoDb in SpringBoot 【发布时间】:2020-07-18 01:25:29 【问题描述】:

我正在尝试通过我的 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。如果有人可以指导我这将非常有帮助。

【问题讨论】:

【参考方案1】:

您只能使用带有find 查询的投影 获取指定字段。尝试使用 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"

【讨论】:

以上是关于如何在 Spring Boot 中从 MongoDb 中仅读取特定的 JSON 节点的主要内容,如果未能解决你的问题,请参考以下文章