springboot整合mongodb批量修改和添加索引

1:创建字段索引

collection 是集合名称,keys 是一个包含一个或多个字段名,options是排序方向,1正序,-1倒叙

db.collection.createIndex(keys, options)
#单字段
db.collection.createIndex(name: 1)
#多字段
db.collection.createIndex{name: 1, age: -1}

2:mongodb批量修改

BulkOperations bulkOperations = mongoTemplate.bulkOps(BulkMode.UNORDERED, RealtimeEntity.class);

updateList.forEach(realtimeEntity -> {
    Query query = new Query(Criteria.where("pn").is(realtimeEntity.getPn()));
    Update update = new Update()
            .set("pnVal", realtimeEntity.getPnVal())
            .set("tm", realtimeEntity.getTm())
            .set("rm", realtimeEntity.getRm());

    bulkOperations.updateOne(query, update);
});
bulkOperations.execute();

注意:必须创建索引这样更新的效率快

你可能感兴趣的:(spring,boot,mongodb,后端)