Search code examples
javamongodbmorphia

how to save a collection of objects to MongoDB with Morphia?


I am currently iterating over a collection of objects and saving them one by one. I suppose there is a way to save the entire collection directly?

Note, I would need to be able to retrieve each individual objects later (not the whole collection).


Solution

  • From the javadoc of the DataStore class. The might not be available on older versions. Even this I think is internally iterating and saving one at a time - but it might get optimized, so it is better to use this than iterate yourself.

    <T> Iterable<Key<T>>
    save(Iterable<T> entities) 
              Saves the entities (Objects) and updates the @Id field
    <T> Iterable<Key<T>>
    save(Iterable<T> entities, com.mongodb.WriteConcern wc) 
              Saves the entities (Objects) and updates the @Id field, with the WriteConcern
    <T> Iterable<Key<T>>
    save(T... entities) 
              Saves the entities (Objects) and updates the @Id field
    

    http://morphia.googlecode.com/svn/site/morphia/apidocs/com/google/code/morphia/Datastore.html#save(java.lang.Iterable)