mongoTemplate批量新增或者更新

// list为要更新或者新增的数据,使用时填充上自己的数据集合
List<MultiAnalyseMakeModel> list = new ArrayList();

List<Pair<Query, Update>> updateList = new ArrayList<>(list.size());
        BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collection);// collection为集合名称
        list.forEach(data -> {
            Query query = new Query(new Criteria("_id").is(data.getId()));
            Update update;
            Document doc = new Document();
            mongoTemplate.getConverter().write(data, doc);
            update = Update.fromDocument(new Document("$set", doc));
            Pair<Query, Update> updatePair = Pair.of(query, update);
            updateList.add(updatePair);
        });
        operations.upsert(updateList);

        BulkWriteResult result = operations.execute();


版权声明:本文为u012294724原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。