List<UpdateOneModel<Entity>> requests = new List<UpdateOneModel<Entity>>(entities.Count()); foreach (var entity in entities) { var filter = new FilterDefinitionBuilder<Entity>().Where(m => m.Field1 == entity.Field1 && m.Field2== entity.Field2); var update = new UpdateDefinitionBuilder<Entity>().Set(m => m.Field1, entity.Field1).Set(m => m.Field2, entity.Field2); var request = new UpdateOneModel<Entity>(filter, update); request.IsUpsert = true; requests.Add(request); } await Collection.BulkWriteAsync(requests);
http://stackoverflow.com/questions/34543056/mongodb-c-sharp-driver-upsert-many-based-on-candidate-key
我的:
var advisorEmails = Database.GetCollection<AdvisorEmail>(Settings.AdvisorEmailCollection).Find(Builders<AdvisorEmail>.Filter.In(x => x.Id, dicAdvisorEmail.Keys)).ToList(); if (advisorEmails != null && advisorEmails.Count > 0) { List<UpdateOneModel<AdvisorEmail>> lstUpdateActions = new List<UpdateOneModel<AdvisorEmail>>(); List<string> lstRemoveAdvisorEmailIds = new List<string>(); foreach (AdvisorEmail advisorEmail in advisorEmails) { if (dicAdvisorEmail.ContainsKey(advisorEmail.Id)) { List<string> lstRemoveIds = dicAdvisorEmail[advisorEmail.Id]; List<string> lstnewIds = new List<string>(); foreach (string s in advisorEmail.ClientIds) { if (!lstRemoveIds.Contains(s)) lstnewIds.Add(s); } if (lstnewIds.Count > 0) { var filter = new FilterDefinitionBuilder<AdvisorEmail>().Where(m => m.Id == advisorEmail.Id); var update = new UpdateDefinitionBuilder<AdvisorEmail>().Set(m => m.ClientIds, lstnewIds); var action = new UpdateOneModel<AdvisorEmail>(filter, update); action.IsUpsert = true; lstUpdateActions.Add(action); } else { lstRemoveAdvisorEmailIds.Add(advisorEmail.Id); } } } if (lstUpdateActions.Count > 0) Database.GetCollection<AdvisorEmail>(Settings.AdvisorEmailCollection).BulkWrite(lstUpdateActions); if (lstRemoveAdvisorEmailIds.Count > 0) LocalAdvisorEmailDB.DeleteMany(Filter<AdvisorEmail>().In(x => x.Id, lstRemoveAdvisorEmailIds)); }