首页 > 代码库 > c# mongo 数组里对象更新

c# mongo 数组里对象更新

var queryDetail = new BsonDocument("cNo", doc.cNo);
                    queryDetail.AddRange(new BsonDocument("Details.dDate", doc.oRDate));

                    //日表数组中存在相同报表日期的数据
                    bool exist = tblDays.FindSync(queryDetail).Any();
                    if (exist)
                    {
                        #region 日表数组中存在相同报表日期的数据,则按字段更新

                        List<WriteModel<BsonDocument>> requests = new List<WriteModel<BsonDocument>>();
                        requests.Add(new UpdateOneModel<BsonDocument>(_query, update) { IsUpsert = true });

                        var updateDetail = new BsonDocument();
                        foreach (var propert in properties)
                        {
                            var vals = propert.GetValue(detail);
                            if (propert.PropertyType.BaseType.Name.Equals("Enum"))
                            {
                                vals = Convert.ToInt64(vals);
                            }
                           
                            var tmpUpdate = new BsonDocument() { { "$set", new BsonDocument() { { string.Format("Details.$.{0}", propert.Name), BsonDocumentWrapper.Create(vals) } } } };

                            requests.Add(new UpdateOneModel<BsonDocument>(queryDetail, tmpUpdate) { IsUpsert = true });
                        }
                        if (requests.Count > 0)
                        {
                            tblDays.BulkWrite(requests);
                        }

                        #endregion
                    }

else                    {
                        #region 日表数组中不存在相同报表日期的数据,则直接新增到数组

                        var updateSet = new BsonDocument() { { "$addToSet", new BsonDocument() { { "Details", BsonDocumentWrapper.Create(detail) } } } };
                        update.AddRange(updateSet);

                        tblDays.UpdateOne(_query, update, new UpdateOptions { IsUpsert = true });

                        #endregion
                    }

c# mongo 数组里对象更新