下面列出了com.mongodb.client.model.UpdateOptions#upsert ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 更新或插入数据集合
*
* @param dbName
* @param collectionName
* @param document
* @param filter
* @return
*/
public boolean upsertMany(String dbName, String collectionName, Document document, Document filter) {
if (document != null) {
UpdateOptions updateOptions = new UpdateOptions();
updateOptions.upsert(true);
mongoClient.getDatabase(dbName).getCollection(collectionName).updateMany(filter, document, updateOptions);
return true;
}
return false;
}
public void Save(Document doc) {
if (!doc.containsKey("_id")) {
Create(doc);
return;
}
Document find = new Document("_id", doc.get("_id"));
UpdateOptions uo = new UpdateOptions();
uo.upsert(true);
ops.add(new ReplaceOneModel<Document>(find, doc, uo));
FlushOpsIfFull();
}
private <T> OpResult addOrReplace(MongoCollection<Document> collection, T t) {
BsonDocument filter = new BsonDocument();
if (t instanceof StreamDefinition) {
filter.append("streamId", new BsonString(MetadataUtils.getKey(t)));
} else if (t instanceof AlertPublishEvent) {
filter.append("alertId", new BsonString(MetadataUtils.getKey(t)));
} else {
filter.append("name", new BsonString(MetadataUtils.getKey(t)));
}
String json = "";
OpResult result = new OpResult();
try {
json = mapper.writeValueAsString(t);
UpdateOptions options = new UpdateOptions();
options.upsert(true);
UpdateResult ur = collection.replaceOne(filter, Document.parse(json), options);
// FIXME: could based on matched count do better matching...
if (ur.getModifiedCount() > 0 || ur.getUpsertedId() != null) {
result.code = 200;
result.message = String.format("update %d configuration item.", ur.getModifiedCount());
} else {
result.code = 500;
result.message = "no configuration item create/updated.";
}
} catch (Exception e) {
result.code = 500;
result.message = e.getMessage();
LOG.error("", e);
}
return result;
}
/**
* Perform upsert: update single element or inserts a new one if none of the document matches.
* <p>
* <em>Note: Upsert operation requires special care to set or init all required attributes in case of insertion
* (including but not limited to '_id'), so that valid document could be inserted into collection.
* </em>
* @return future of number of processed document (expected to be 1)
*/
public FluentFuture<Integer> upsert() {
UpdateOptions options = new UpdateOptions();
options.upsert(true);
return repository.doUpdate(criteria, collectRequiredUpdate(), options);
}