Reputation: 271
I am trying to get the number of documents that have a field with an empty string. This field, lets call it "Field_One" is present in all documents (so, to be clear, I am not trying to find if the field exists or not, I want to find which documents have nothing (empty string) in 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 it doesn't work (they return all the 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 this, it wont actually retrieve the documents from the database to my program, so the count calculation is done in the MongoDB server.
Upvotes: 7
Views: 16269
Reputation: 1708
Assuming that you are querying for documents of a class looking something like:
public class MyClass {
public string Field_One { get; set; }
//... other attributes, constructors, methods etc...
}
You can also write your query using expression lambdas like this for example:
var res = collection.Find(Query<MyClass>.NE(m => m.Field_One, BsonString.Empty)).Count();
Upvotes: 0
Reputation: 593
BsonNull.Value
translates into null
BsonString.Empty
translates into ""
BsonObject.Create("")
translates into "" as well
collection.Find(Query.NE("Field_One", BsonString.Empty)).Count()
translates into "Field_One": { "$ne": "" }
what should be exactly what you are looking for if the field is actually filled with ""
Upvotes: 13
Reputation: 635
In order to test a string isn't empty, in Javascript it is simply :
collection.find({Field_One:{ $ne: "" }})
see $ne. I can't help you translating that into C# driver language.
Upvotes: 7