1

Currently, we're looking for a solution to save the following User entity into multiple MongoDB collections at the same time (i.e. db_users and on db_users_legacy). Both collections are in the same database.

Please don't ask me the reason why I need to save in two collections. It is a business requirement.

@Document(collection = "db_users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @Id
    private String id;
    private String name;
    private String website;
    private String name;
    private String email;

}

And my SpringBoot application configuration goes as;

@Configuration
public class ApplicationConfig {

    @Bean
    public MongoTemplate mongoTemplate(MongoDbFactory factory){
        MongoTemplate template = new MongoTemplate(factory);
        template.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        retu,rn template;
    }

}

Currently my repository looks as this. And saving works perfectly fine. How can I same this document in two different collections?

@Repository
public class UserRepositoryImpl implements UserRepository {

    private MongoTemplate mongoTemplate;

    public UserRepositoryImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void save(User user) {
        mongoTemplate.save(user);
    }

}

Can anyone suggest the best option to deal with this, please?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Nilanchala
  • 5,891
  • 8
  • 42
  • 72

1 Answers1

7

I suggest using MongoTemplate's the other overloaded save method.

@Override
public void save(User user) {
    mongoTemplate.save(user, "db_users");
    mongoTemplate.save(user, "db_users_legacy");
}

This can be used to save same object to multiple collections. From docs,

You can customize this by providing a different collection name using the @Document annotation. You can also override the collection name by providing your own collection name as the last parameter for the selected MongoTemplate method calls.

So it doesn't matter the collection name specifically provided in @Document, you can always override it using MongoTemplate.

Community
  • 1
  • 1
benjamin c
  • 2,278
  • 15
  • 25
  • Thanks, Ben for your reply. This looks like the easiest way to handle. But was looking if any alternative solution available. – Nilanchala Sep 11 '18 at 20:19