问题
jdbcTemplate.batchUpdate("INSERT INTO TABLE_NAME (COL1, COL2, COL3) VALUES (?, ?, ?)", List<Object[]>);
Is there a similar way that I can do same insert using MongoRepository
Interfaces in Spring data
mongodb
and java
?
回答1:
You can insert multiple documents into the collection using one of the following methods. Assuming a test
collection and a Test.java
POJO representng a document:
(i) Inserting and Deleting using the MongoRepository
:
@Repository
public interface MyRepository extends MongoRepository<Test, String> {
void deleteByIdIn(List<ObjectId> ids);
}
// Run the saveAll
repository method:
Test t1 = new Test("apple");
Test t2 = new Test("banana");
Test t3 = new Test("orange");
List<Test> ts = repository.saveAll(Arrays.asList(t1, t2, t3));
From the Mongo Shell lookup the newly inserted documents in the test
collection:
> db.test.find()
{ "_id" : ObjectId("5e579153c4d0e55b6ad5f869"), "name" : "apple", "_class" : "com.example.demo.Test" }
{ "_id" : ObjectId("5e579153c4d0e55b6ad5f86a"), "name" : "banana", "_class" : "com.example.demo.Test" }
{ "_id" : ObjectId("5e579153c4d0e55b6ad5f86b"), "name" : "orange", "_class" : "com.example.demo.Test" }
// Perform Delete by ids:
ObjectId o1 = new ObjectId("5e579153c4d0e55b6ad5f869"); // apple
ObjectId o2 = new ObjectId("5e579153c4d0e55b6ad5f86b"); // orange
List<ObjectId> ids = Arrays.asList(o1, o2);
repository.deleteByIdIn(ids);
The objects with names "apple" and "orange" will be deleted. Also, note that the Test.java
POJO class must have the id
field defined to refer and delete by that field.
(ii) Using MongoTemplate
:
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
BulkOperations bulkOps = mongoOps.bulkOps(BulkOperations.BulkMode.UNORDERED, Test.class);
Test t1 = new Test("orange");
Test t2 = new Test("grape");
bulkOps.insert(Arrays.asList(t1, t2));
BulkWriteResult r = bulkOps.execute();
(iii) The POJO Test
Class:
public class Test {
private String id;
private String name;
public Test(String name) {
this.name = name;
}
public String getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
}
来源:https://stackoverflow.com/questions/60428078/how-to-perform-bulk-operation-in-mongodb-similar-to-jdbdtemplate-batchupdate