How to check that the string field in a MongoDB document is not empty?

I am trying to get the number of documents that have a field with an empty string. This field allows you to call it "Field_One" is present in all documents (therefore, to be clear, I am not trying to find whether this field exists or not, I want to find which documents have nothing (empty line) in the field "Field_One" " .

I tried using (using the C # driver):

collection.Find(Query.NE("Field_One", BsonNull.Value)).Count() collection.Find(Query.NE("Field_One", BsonString.Null)).Count() 

and even (someone suggested this somewhere):

 collection.Find(Query.GT("Field_One", BsonString.Empty)).Count() 

But this will not work (they return all documents).

Also, as a related question: Is this the best way to get the number of matching documents in a collection? As far as I understand, it usually does not extract documents from the database into my program, so the counter is calculated on the MongoDB server.

+7
source share
3 answers

BsonNull.Value means null
BsonString.Empty means "
BsonObject.Create("") also means <">

  collection.Find(Query.NE("Field_One", BsonString.Empty)).Count() 

translates to "Field_One": { "$ne": "" } what should be exactly what you are looking for if the field is really filled with the symbol ""

+10
source

To check a string is not empty, in Javascript it's simple:

 collection.find({Field_One:{ $ne: "" }}) 

see $ ne . I cannot help you translate this into the C # driver language.

+7
source

Assuming you are requesting class documents that look something like this:

 public class MyClass { public string Field_One { get; set; } //... other attributes, constructors, methods etc... } 

You can also write your query using the lambdas expression, for example:

 var res = collection.Find(Query<MyClass>.NE(m => m.Field_One, BsonString.Empty)).Count(); 
0
source

All Articles