• Mongodb 批量Upsert


            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));
    					}
    

      

  • 相关阅读:
    20165319第五周java学习笔记
    20165319 20165335 结对学习创意照
    20165215 结对编程——四则运算第二周
    20165215 2017-2018-2 《Java程序设计》第八周学习总结
    2017-2018-2 20165215 实验二 Java面向对象程序设计
    20165215 结对编程——四则运算第一周
    20165215 2017-2018-2 《Java程序设计》第7周学习总结
    20165215 2017-2018-2 《Java程序设计》第6周学习总结
    20165215 实验一 Java开发环境的熟悉
    20165215 2017-2018-2 《Java程序设计》第5周学习总结
  • 原文地址:https://www.cnblogs.com/Cavalry/p/6603470.html
Copyright © 2020-2023  润新知