簡體   English   中英

如何使用C#檢查特定文檔Mongodb中是否存在字段?

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

我有一個帶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();

您可以嘗試以下方法:

  1. 使用“嘗試/捕獲”,如下所示:

     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 

希望能有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM