Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query if array is null or empty using MongoDB and C# Driver?

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:

  1. What C# Driver method should I use to query if an array is empty?
  2. Or, what is the best way to check if an array is null or empty?

Any help with this would be greatly appreciated! :)

like image 217
Steve Konves Avatar asked Jun 13 '12 19:06

Steve Konves


2 Answers

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

like image 80
Craig Wilson Avatar answered Oct 05 '22 22:10

Craig Wilson


$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 }]}

like image 29
Poorna Subhash Avatar answered Oct 06 '22 00:10

Poorna Subhash