很多同学都学会了怎么使用changeStream去监听mongo数据库日志,但是有部分同学不知道怎么去使用它,下面用几个简单的代码说明。
1-数据填充
@Data
public class MongoLog {
/**
* 集合名称
*/
private String collectName;
/**
* 操作类型
*/
private String operationType;
/**
* 全部文档数据
*/
private String fullDocument;
/**
* 更新的字段数据
*/
private String updateMapFileId;
/**
* 主键id- 对应的key
*/
private String _id;
}
2-填充实体
String operT = change.getOperationType().getValue().toLowerCase();
String key = null;
BsonDocument bsonDocumentKey = changeStreamDocument.getDocumentKey();
if (bsonDocumentKey != null) {
if (bsonDocumentKey.isDouble("_id")) {
key = String.valueOf(bsonDocumentKey.getDouble("_id").getValue());
} else if (bsonDocumentKey.isNumber("_id")) {
key = String.valueOf(bsonDocumentKey.getNumber("_id").intValue());
} else if (bsonDocumentKey.isInt32("_id")) {
key = String.valueOf(bsonDocumentKey.getInt32("_id").getValue());
} else if (bsonDocumentKey.isInt64("_id")) {
key = String.valueOf(bsonDocumentKey.getInt64("_id").getValue());
} else if (bsonDocumentKey.isString("_id")) {
key = bsonDocumentKey.getString("_id").getValue();
} else if (bsonDocumentKey.isObjectId("_id")) {
key = bsonDocumentKey.getObjectId("_id").getValue().toString();
}
}
MongoLog mongoLog = new MongoLog();
mongoLog.setCollectName(collectionName);
mongoLog.setOperationType(operT);
mongoLog.set_id(key);
mongoLog.setFullDocument(changeStreamDocument.getFullDocument() != null ? changeStreamDocument.getFullDocument().toJson() : "");
UpdateDescription description = changeStreamDocument.getUpdateDescription();
if (description != null && description.getUpdatedFields() != null) {
mongoLog.setUpdateMapFileId(description.getUpdatedFields().toJson());
}
接收的数据以上就差不服了, 新增使用fullDocument 更新使用 updateMapFile 以及对应的id,删除使用 id.
2-使用使用,这里我这使用的springboot 的 mongoTempdate
保存: CollectionNameX collectionNameX = mongoTemplate.getConverter().read(CollectionNameX.class, fullDocument); mongoTemplate.save(integralDetails,collectionName);
注:CollectionNameX 这个是数据库的集合实体,你们根据自己实际的表实体定义
更新:
Query query = new Query(new Criteria().andOperator(Criteria.where("_id").is(mongoLog.get_id())));
Update update = new Update();
for(Map.Entry<String,BsonValue> entry:bsonDocument.entrySet()){
update.set(entry.getKey(),entry.getValue());
}
UpdateResult updateResult = mongoTemplate.upsert(query,update,collectionName);
删除根据id删除就可以了。
1万+

被折叠的 条评论
为什么被折叠?



