0

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 Answer 1

1

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"}}}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.