Reputation: 1360
I have a document in my MongoDb database, and I want to write a query to retrieve documents whose array size is greater than 0 (array is not null or empty to be clear).
Here is my C# code givent the fact that Quotes
is my subarray :
internal bool HasQuote(string projectNumber)
{
var filter = Builders<Entity.Project>.Filter.Eq(x => x.ProjectNumber, projectNumber);
filter &= Builders<Entity.Project>.Filter.Exists(x => x.Quotes);
filter &= Builders<Entity.Project>.Filter.SizeGt(x => x.Quotes.Count, 0);
var res = _mongoCollection.CountDocuments(filter);
return res > 0;
}
Unfortunately the function returns all time false
. It must be related to the SizeGt
part, because when I remove this line it is working fine.
I tryed other stuff like filter &= Builders<Entity.Project>.Filter.Where(x => x.Quotes.Count > 0);
or filter &= Builders<Entity.Project>.Filter.Exists(x => x.Quotes[0]);
Upvotes: 0
Views: 949
Reputation: 11364
What does SizeGT takes in as parameters?
SizeGt(FieldDefinition<TDocument> field, int size);
which means you have to provide a Field that you need to get a count on.
What to do to fix your code
Change the line:
filter &= Builders<Entity.Project>.Filter.SizeGt(x => x.Quotes.Count, 0);
to this
filter &= Builders<Entity.Project>.Filter.SizeGt(x => x.Quotes, 0);
Reason you dont provide the Count is because SizeGT knows how to Convert x.Quotes and get a count of it. If you do a count and catch the error, you'll get the error:
Unable to determine the serialization information for x => Convert(x.Quotes.Count).
I just ran the code above on my list and it came back with correct numbers.
Upvotes: 1