如何使用C#检查特定文档Mongodb中是否存在字段? [英] how to check if a field exists in a specific document Mongodb using C#?
问题描述
我有一个带有 asp.Net/C# 的 WebAPI,我正在使用 Mongodb.在更新特定文档之前,我需要检查文档中是否存在某个字段,如果不存在,则将该字段添加到文档中.但是我不知道如何检查文档中是否存在字段.要添加我使用此代码的字段:
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);
提前致谢.
我尝试使用类似的东西,但它返回空值!!
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();
推荐答案
您可以尝试以下操作:
按如下方式使用 Try/Catch:
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
}
使用.Contains(),如下:
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...
并且通过使用 TryGetElement,您还可以获得此元素:
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
希望有帮助
这篇关于如何使用C#检查特定文档Mongodb中是否存在字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!