如何使用C#检查一个字段是否存在于一个特定的文档Mongodb中?

3qpi33ja  于 2022-11-22  发布在  Go
关注(0)|答案(2)|浏览(138)

我有一个使用asp.NET/C#的WebAPI,我使用的是Mongodb。在更新一个特定的文档之前,我需要检查文档中是否存在一个字段,如果不存在,则将该字段添加到文档中。但是我不知道如何检查文档中是否存在一个字段。要添加字段,我使用以下代码:

var update = Bundle.Update.Set(b => b.followers, new List<User>());
int res = Bundle.UpdateOne(Bundle.Filter.Eq(b => b._id, id), update);

先谢谢你。
我尝试使用类似的内容,但它返回null!!

var builder = Builders<BsonDocument>.Filter;               
var filter = builder.Exists("followers", false).ToBsonDocument();
var RetrievedData = Bundle.Collection().Find(filter).ToList();
ecbunoof

ecbunoof1#

您可以尝试以下操作:
1.按如下方式使用Try/Catch:

var document = Bundle.Collection().Find(filter); // here is your BsonDocument
try
   {
      document["fieldNameToCheck"] // if field doesn`t exist it throws KeyNotFoundException. If there are nested objects just follow the pattern: document["fieldName"]["fieldNestedToCheck"]
   }
catch (Exception ex) when (ex is KeyNotFoundException)
   {
      // your logic for "the field wasn`t found in the document" case
   }

1.使用.Contains(),如下所示:

var exists = document.Contains("fieldNameToCheck");// if field exists it returns true
// If you need to check the nested fields, you can do as follows:
var nestedExists = document["fieldName"].ToBsonDocument().Contains("fieldNameToCheck"); // or:
var nestedExists = document["fieldName"]["nestedFieldNameNextLevel"].ToBsonDocument().Contains("fieldNameToCheck");  // and so on...

1.通过使用TryGetElement,您还可以获得以下元素:

BsonElement element; // it will contain found element if true for next line
var exists =  document.TryGetElement("fieldNameToCheck", out element); // returns true if element is found

希望对你有帮助

bvhaajcl

bvhaajcl2#

您可以通过检查Bson值来检查文档中是否存在字段:

if (!document["fieldNameToCheck"].AsBsonValue is BsonNull)
{
   // the field exist...
}

相关问题