Reputation: 137
I'm trying to update the value of a single field of a stored JSON in MongoDb from Springboot
. I'm not using POJO
since the JSON
schema will be random always.
// this is what I'm trying to achieve. But I don't know how to do it from SpringBoot.
db.collection.update( { _id:12345} , { $set: { a.b.c.d : updatedValue } }
This is how I saved my JSON
Object to MongoDB
:
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("dbOne");
DBCollection collection = db.getCollection("data");
// convert JSON to DBObject directly
DBObject dbObject = (DBObject) JSON.parse(jsonString);
collection.insert(dbObject);
My JSON
sample data:
{
"a":{
"b":{
"c":{
"d":"value1",
"e":"value2"
}
}
}
}
Upvotes: 1
Views: 909
Reputation: 219
Yes you can do it via mongoOperations and Update API. This will allow you to update individual fields in a mongodb collection- Ex:
Query query = new Query(new Criteria("id").is(12345L));
Update updateOp = new Update().set("a.b.c.d", value);
mongoOperations.updateFirst(query, updateOp, COLLECTION);
Upvotes: 3