Insert Documents in various Collections in single DB

Hello! :slight_smile:
What is the best way to insert documents in various collections in Java?
Now I created a simple class with @Document annotation in which there is SpEL sentence with getting collectionName (see later) from Spring bean (I’m setting new collectionName in it before insertion), but I think it is not the best way…
So, I have single DB, e.g. TestDB, and it has many collections, e.g. Collection_1, Collection_2 and etc… In code I must choose to which collection insert document.
So, collectionNameHolder has just String collectionName;.
Class for document:

@Document(collection = “#{collectionNameHolder.getCollectionName()}”)
class TestDocument {
    …
}

Insertion:

collectionNameHolder.setCollectionName(NEW_COLLECTION_NAME);
testDocumentRepository.save(testDocument);

I work with Spring Data…

I do not know if it is the best. I know it is the simplest.

Forgo all extra layers and simply use

MongoClient mongo = ...
MongoDatabase database = mongo.getDatabase( "TestDB" ) ;
MongoCollection<Document> collection = database.getCollection( "Collection_1" ) ;
Document testDocument = ...
collection.insertOne( testDocument ) ;

https://mongodb.github.io/mongo-java-driver/3.6/javadoc/?com/mongodb/client/MongoCollection.html

https://mongodb.github.io/mongo-java-driver/3.6/javadoc/com/mongodb/client/MongoDatabase.html

https://mongodb.github.io/mongo-java-driver/3.6/javadoc/com/mongodb/MongoClient.html

https://mongodb.github.io/mongo-java-driver/3.6/javadoc/org/bson/Document.html

1 Like