我想将Id
字段除C# MongoDB official driver 2.4.4
以外的完整文档
从API documention
我可以创建UpdateDefinination
,如下所示
var filter = Builders<Shipment>.Filter.Where(_ => _.ShipmentIdentifier == shipment.ShipmentIdentifier);
var options = new FindOneAndUpdateOptions<Shipment>() { IsUpsert = true };
var update = BuildUpdateDefination(shipment);
var updatedEntity = collection.FindOneAndUpdate(filter, update, options);
此代码适用于以下BuildUpdateDefination
private UpdateDefinition<Shipment> BuildUpdateDefination(Shipment shipment)
{
var update = Builders<Shipment>.Update.Set(_ => _.Carrier, shipment.Carrier)
.Set(_ => _.Addresses, shipment.Addresses)
.Set(_ => _.Attributes, shipment.Attributes)
.Set(_ => _.CarrierCashOnDeliveryAmount, shipment.CarrierCashOnDeliveryAmount)
.Set(_ => _.CarrierInsuranceAmount, shipment.CarrierInsuranceAmount)
.Set(_ => _.CarrierRoutingError, shipment.CarrierRoutingError)
.Set(_ => _.CarrierRoutingValue1, shipment.CarrierRoutingValue1)
.Set(_ => _.CarrierRoutingValue2, shipment.CarrierRoutingValue2)
.Set(_ => _.CarrierRoutingValue3, shipment.CarrierRoutingValue3)
.Set(_ => _.CarrierRoutingValue4, shipment.CarrierRoutingValue4)
.Set(_ => _.CarrierRoutingValue5, shipment.CarrierRoutingValue5)
.Set(_ => _.CarrierService, shipment.CarrierService)
.Set(_ => _.CarrierServiceAttributes, shipment.CarrierServiceAttributes)
.Set(_ => _.CashOnDeliveryReference, shipment.CashOnDeliveryReference)
.Set(_ => _.Currency, shipment.Currency)
.Set(_ => _.DeliveryInstruction1, shipment.DeliveryInstruction1)
.Set(_ => _.DeliveryInstruction2, shipment.DeliveryInstruction2)
.Set(_ => _.DeliveryInstruction3, shipment.DeliveryInstruction3);
return update;
}
但问题是Shipment
有许多字段需要更新。那么更新对象的所有属性有什么更好的方法?
我试图迭代对象的所有属性,如下所示,但这也无法正常工作
var updateSet = new List<UpdateBuilder>();
Type type = shipment.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (!property.Name.Equals("Id") && !property.Name.Equals("ShipmentIdentifier"))
updateSet.Add(Update.Set(property.Name, (BsonValue)property.GetValue(shipment) ?? BsonNull.Value));
}
var update = Update<Shipment>.Combine(updateSet).ToBsonDocument();
我一直在寻找,但没有得到任何有效的解决方案。
答案 0 :(得分:0)
您尝试过Collection.FindOneAndReplace()
吗?
您可以使用它来替换对象,并设置isUpsert
属性以向上插入文档。