使用MongoDB C#驱动程序2.0添加元素或添加到数组 [英] Add element or add to array using MongoDB C# driver 2.0

查看:55
本文介绍了使用MongoDB C#驱动程序2.0添加元素或添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档,上面可以有一个"Favorites"元素,并且我正在尝试将新值推入该元素的数组中.但是,出现错误是因为我要更新的文档没有收藏夹"元素.如果不存在该如何创建元素,以便可以将新值推入它的array属性中?我可以一次操作吗?这是我正在做的事情,但出现错误无法使用零件("Favorites of收藏夹.ProgramIds")遍历元素({Favorites:null})

I have a document that can have a "Favorites" element on it and I'm trying to push a new value into an array on that element. However, I'm getting an error because the document I'm trying to update doesn't have the "Favorites" element. How can I create the element if it doesn't exist so I can push the new value into it's array property? Can I do it in one operation? Here's what I'm doing, but I get the error cannot use the part (Favorites of Favorites.ProgramIds) to traverse the element ({Favorites: null})

var filter = Builders<UserEntity>.Filter.Eq(u => u.Id, userId);
var update = isFavorite ? Builders<UserEntity>.Update.AddToSet(u => u.Favorites.ProgramIds, id)
    : Builders<UserEntity>.Update.Pull(u => u.Favorites.ProgramIds, id);
await collection.UpdateOneAsync(filter, update);

推荐答案

如果Favorities数组有可能为null,则必须在使用"addToSet"或"push"之前创建该数组,否则会出现错误:

If there are possibilities that the Favorities array can be null you have to create the array before use "addToSet" or "push" otherwise you get the error:

MongoDB.Driver.MongoWriteException:'写入操作导致错误.无法将$ addToSet应用于非数组字段.名为收藏夹"的字段的非数组类型为null'

在下面的示例中,如果数组为null,则设置一个新数组

Below an example where if the array is null a new one is set

            var filter = Builders<UserEntity>.Filter.Eq(u => u.Id, userId);
            if (!isTheFavoritesArrayNotNull)
            {
                await collection.UpdateOneAsync(filter,
                    isFavorite ? Builders<UserEntity>.Update.Set(u => u.Favorites, new List<Favorite>()));
            }
            await collection.UpdateOneAsync(filter,
                    Builders<UserEntity>.Update.AddToSet(u => u.Favorites.ProgramIds, id));

这篇关于使用MongoDB C#驱动程序2.0添加元素或添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆