问题
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:
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 }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...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