【问题标题】:how to check if a field exists in a specific document Mongodb using C#?如何使用 C# 检查特定文档 Mongodb 中是否存在字段?
【发布时间】:2018-06-12 19:31:54
【问题描述】:

我有一个带有 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();

【问题讨论】:

  • 你能告诉我们你已经尝试过什么吗?
  • @Dave 我在我尝试的最后一件事上添加了但没有成功!!

标签: c# mongodb


【解决方案1】:

您可以尝试以下方法:

  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
       } 
    
  2. 使用.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...      
    
  3. 通过使用 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
    

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多