Reputation: 1555
I'm trying to figure out how to persist a semi-structured document to MongoDB, using Spring Mongo. Here's an example of what I'm trying to accomplish:
{
"name": "Test",
"admin": false,
"unstructured_field_one": "Some arbitrary data"
}
I know how to do this with fully unstructured data as a field in a parent document, where I can just use something like
//...
private Object someRandomObject;
But how can I accomplish a semi-structured document (at parent level), where I have, as in the example, name
and admin
as required fields, and whatever else comes in along with the request gets added automagically?
Upvotes: 2
Views: 568
Reputation: 27048
You can do it without any pojo, just with a Json Parser(Jackson) and MongoTemplate
. Since MongoTemplate can save any DbObject, You need to convert your json to a DBObject.
Something like this will do
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String,Object>> typeRef
= new TypeReference<Map<String,Object>>() {};
Map<String,Object> map = mapper.readValue(json, typeRef);
DBObject dbObject = new BasicDBObject(map);
mongoTemplate.getCollection("blahblah").save(dbObject);
Upvotes: 2