Search code examples
c#linqmongodbmongodb-.net-driver

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! :)


Solution

  • 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