MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

come verificare se esiste un campo in un documento specifico Mongodb usando C#?

Puoi provare quanto segue:

  1. Usa Prova/Riprendi come segue:

    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. Usa .Contains(), come segue:

    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. E usando TryGetElement puoi anche ottenere questo elemento:

    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
    

Spero che sia stato d'aiuto