mongodb批量更新,如果不存在则自动插入

驱动名称:
MongoDB.Driver

重要特性:


        public async Task BatchSave<T>(string collectionName, List<T> entities) where T : BsonDocument
        {
            var collection = _database.GetCollection<T>(collectionName);

            var models = new List<WriteModel<T>>();

            foreach (var item in entities)
            {
                if (!item.Contains("_id"))
                {
                    continue;
                }

                var filter = Builders<T>.Filter.Eq("_id", item.GetValue("_id"));
                models.Add(new ReplaceOneModel<T>(filter, item) { IsUpsert = true });

            }

            await collection.BulkWriteAsync(models, new BulkWriteOptions { IsOrdered = false });
        }

posted on 2021-08-03 14:37  隨風.NET  阅读(1275)  评论(0编辑  收藏  举报

导航