Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a 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, 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.

like image 358
Erick Tejada Avatar asked Apr 17 '13 16:04

Erick Tejada


1 Answers

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 ""

like image 175
AirBorne04 Avatar answered Nov 15 '22 20:11

AirBorne04