Java MongoDb 批量插入或修改
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.*;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
@RestController
@RequestMapping("/mongo")
@Slf4j
public class TestMongoController {
@Autowired
private MongoDbFactory mongoDbFactory;
private MongoDatabase db;
private String test_upsert_bulk = "test_upsert_bulk";
@GetMapping("/getAll")
public List<Document> getAll() {
List<Document> result = new LinkedList<>();
MongoDatabase db = getDb();
Document project = new Document("_id", 0);
project.put("id", 1);
project.put("name", 1);
project.put("age", 1);
db.getCollection(test_upsert_bulk).find().projection(project).into(result);
return result;
}
@GetMapping("/upserts")
public String upserts(Integer baseInt) {
LinkedList<WriteModel<Document>> writeModels = new LinkedList<>();
writeModels.add(getBulkInsert(3, "insert", baseInt + 1));
writeModels.add(getBulk(1, "upsert1", 19 + baseInt));
writeModels.add(getBulk(2, "upsert2", 18 + baseInt));
log.info("size {}: , \n list: {}", writeModels.size(), writeModels);
BulkWriteOptions bulkWriteOptions = new BulkWriteOptions();
bulkWriteOptions.ordered(true);
getDb().getCollection(test_upsert_bulk).bulkWrite(writeModels, bulkWriteOptions);
return "ok";
}
private WriteModel<Document> getBulkInsert(Integer id, String name, Integer age) {
return new InsertOneModel<>(getBase(id, name, age));
}
private WriteModel<Document> getBulk(Integer id, String name, Integer age) {
Document filter = new Document("id", id);
Document name1 = getBase(id, name, age);
UpdateOptions upsert = new UpdateOptions().upsert(true);
return new UpdateOneModel<>(filter, new Document("$set", name1), upsert);
}
private Document getBase(Integer id, String name, Integer age) {
Document result = new Document("id", id);
result.put("name", name);
result.put("age", age);
return result;
}
private MongoDatabase getDb() {
if (Objects.isNull(db)) {
this.db = mongoDbFactory.getDb();
}
return this.db;
}
}