how to check if a field exists in a specific document Mongodb using C#?

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-08 10:02:00

问题


I have a WebAPI with asp.Net/C# and I'm using Mongodb . Before updating a specific document, I need to check if a field exists in the document or not and if not add the filed to the document. But I don't know how I can check the existence of a field in a document. To add the field I'm using this code:

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

Thanks in advance.

I tried to use something like this but it returns null!!

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

回答1:


You can try the following:

  1. Use Try/Catch as follows:

    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. Use .Contains(), as follows:

    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. And by using TryGetElement you can additionally get this element:

    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
    

Hope it helped



来源:https://stackoverflow.com/questions/50824533/how-to-check-if-a-field-exists-in-a-specific-document-mongodb-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!