Background:
What I need to accomplish is to remove any records in a collection if a specific array on the record is null or empty.
I understand that the C# Driver query to find a null array is:
IMongoQuery query = Query.Exists("myArray", false);
That is fine for detecting an null array, but sometimes the array will not be null, but will not have any elements. What I need is more like:
// Note: second subquery will not work
IMongoQuery query = Query.Or(
Query.Exists("myArray", false),
Query.IsEmpty("myArray", false) // error
);
Model:
My class would look like:
public class MyClass
{
// This property may be null or empty
[BsonElement("myArray")]
public string[] MyArray { get; set; }
[BsonElement("someElement")]
public int SomeElement{ get; set; }
}
Summary:
Any help with this would be greatly appreciated! :)
You are looking for the $size operator.
Query.Size("myArray", 0)
will be true if the array is empty.
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size
$exists matches only fields that are not present. If a field is present, but it's value is null (BSON null), then those fields aren't matched by $exists. http://docs.mongodb.org/manual/reference/operator/query/exists/
However, checking the fields value against null matches in both cases: the field doesn't exist, and also the field value is null. http://docs.mongodb.org/manual/faq/developers/#faq-developers-query-for-nulls
So, in this case. It should be OR condition on two criterias: 1. field: null 2. field size =0;
{ "$or" : [ { "MyArray" : { "$size" : 0}} , { "MyArray" : null }]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With