|
| 1 | +package com.hungcdev.insert; |
| 2 | + |
| 3 | +import com.hungcdev.connection.MongoDBConnection; |
| 4 | +import com.hungcdev.data.Post; |
| 5 | +import com.mongodb.client.MongoCollection; |
| 6 | +import com.mongodb.client.MongoDatabase; |
| 7 | + |
| 8 | +import java.util.List; |
| 9 | +import java.util.UUID; |
| 10 | + |
| 11 | +public class InsertDocument { |
| 12 | + private MongoDBConnection mongoDBConnection; |
| 13 | + |
| 14 | + private MongoDatabase mongoDatabase; |
| 15 | + |
| 16 | + public InsertDocument(String ip, int port, String databaseName) { |
| 17 | + this.mongoDBConnection = new MongoDBConnection(); |
| 18 | + this.mongoDBConnection.connectMongoDBWithPOJOs(ip, port); |
| 19 | + this.mongoDatabase = mongoDBConnection.getMongoClient().getDatabase(databaseName); |
| 20 | + } |
| 21 | + |
| 22 | + public <T> void insert(String collectionName, T document , Class<T> classType) { |
| 23 | + MongoCollection<T> collection = mongoDatabase.getCollection(collectionName, classType); |
| 24 | + collection.insertOne(document); |
| 25 | + } |
| 26 | + |
| 27 | + public static void main(String[] args) { |
| 28 | + InsertDocument insertDocument = new InsertDocument("localhost", 27017, "HungcDev"); |
| 29 | + Post post = Post.builder() |
| 30 | + .id(UUID.randomUUID().toString()) |
| 31 | + .title("Mongodb Java tutorial") |
| 32 | + .user("Hungcdev") |
| 33 | + .content("Huong dan intert Document trong MongoDB") |
| 34 | + .tags(List.of("Mongodb", "Mongodb Java")) |
| 35 | + .enable(true) |
| 36 | + .build(); |
| 37 | + insertDocument.insert("Post", post, Post.class); |
| 38 | + System.out.println("Insert Post Successful!"); |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +} |
0 commit comments