Marc Tarin, Mar 25 2016
https://stackoverflow.com/questions/35847165/how-to-use-dynamic-schema-in-spring-data-with-mongodb
First, a few insightful links about schemaless data:
what does “schemaless” even mean anyway?
“schemaless” doesn't mean “schemafree”
Second... one may wonder if Spring, or Java, is the right solution for your problem - why not a more dynamic tool, such a Ruby, Python or the Mongoshell?
That being said, let's focus on the technical issue.
If your goal is only to store random data, you could basically just define your own controller and use the MongoDB Java Driver directly.
If you really insist on having no predefined schema for your domain object class, you can use something like:
@Document(collection = "users")
public class User implements UserDetails {
@Id
private String id;
private Object data;
// getters/setters omitted
}
data could also ne defined as Map, com.mongodb.DBObject, com.mongodb.BasicDBObject or com.mongodb.BasicDBList.
Basically it gives you a field in which you can put whatever you want, but watch out for serialization/deserialization issues (this may become tricky if you had ObjectIds and DBRefs in your nested document). Also, updating data may become nasty if you're data hierarchy becomes too complex.
Still, at some point, you'll realize your data indeed has a schema that can be pinpointed and put into well-defined POJOs.