c# Mongodb批量更新 - 94cool

时间:2024-03-11 19:16:54

c# Mongodb批量更新

public void Put(List<OnlineItem> datas)
        {
            try
            {
                string tblName = datas[0].beginTime.ToString("yyyy-MM-dd");
                MongoCollection<BsonDocument> table = null;

                if (tables.ContainsKey(tblName))
                {
                    table = tables[tblName];
                }
                else
                {
                    table = db.GetCollection(tblName);
                    tables.TryAdd(tblName, table);
                }
                var bulk = table.InitializeOrderedBulkOperation();
                //var update = new UpdateBuilder();

                foreach (var data in datas)
                {
                    data.UpdateTime = DateTime.Now;
                    IMongoQuery query = Query.EQ("Seq", data.Seq);
                    var update = new UpdateDocument() { { "$set", BsonDocumentWrapper.Create(data) } };
                    bulk.Find(query).Update(update);
                }
                bulk.Execute();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "Put");
            }
        }