C# Driver 2.0: elemMatch on Nested array

4,149 views
Skip to first unread message

torn...@gmail.com

unread,
Jun 15, 2015, 11:07:05 AM6/15/15
to mongodb...@googlegroups.com
Hi,
i'm playing around with nested arrays:

Let's say I have the following nested array:

Nested: [[1,2,3][4,5,6][7,8,9]]

Now I want to match all documents with a nested array containing 5.

So in mongo shell my query would look like:

{''Nested": { $elemMatch: {$elemMatch: {$eq: 5} } } }


In the C# 2.0 driver I can't do the nested $elemMatch as it always want's a named field as first parameter. I don't know how to use

The outer one is simple:
var filter = Builders<TParentDocument>.Filter.ElemMatch(t => t.Nested, subFilter);

I tried multiple things for the inner one (and probably a few more I can't remember):
            var subFilter = Builders<IEnumerable<int>>.Filter.ElemMatch(x => x, Builders<int>.Filter.Eq(x => x,5)); // ArgumentNullException
            var subFilter = Builders<IEnumerable<int>>.Filter.ElemMatch("{}", Builders<int>.Filter.Eq("{}",5)); // empty result set
            var subFilter = Builders<IEnumerable<int>>.Filter.ElemMatch(string.Empty, Builders<int>.Filter.Eq(string.Empty, 5)); // Empty result set
            var subFilter = Builders<IEnumerable<int>>.Filter.AnyEq(x => x,5); // ArgumentNullException
            var subFilter = Builders<IEnumerable<int>>.Filter.AnyEq("{}",5); // Empty set



Thanks,
torni,

Craig Wilson

unread,
Jun 15, 2015, 2:28:46 PM6/15/15
to mongodb...@googlegroups.com
Right. That is an interesting problem and one we've encountered before. To support this type of query would mean duplicating almost all of the filter builders to not take a name. While this is tedious for us, if necessary, we should do it. However, the number of users with this problem are very few and the additional overloads would likely be confusing and ultimately allow for some very wrong queries to get built up. We'll keep trying to figure out a better way to handle $elemMatch with scalar arrays. In the meantime, you'll need to build up your filter using a BsonDocument instead of using the builders for this particular example.

torn...@gmail.com

unread,
Jun 15, 2015, 2:49:06 PM6/15/15
to mongodb...@googlegroups.com
Ok, thanks, I'll use the BSONDocument way for now. I agree that too many overloads will confuse people.
I've seen you've added an EmptyFilterDefinition on the github for 2.1, maybe an EmptyFieldDefinition would work for this case, it would still pass all those ArgumentNullChecks, but you would have to handle it in the render code. It might not be totally correct from a naming point of view, as in this case the field is missing and not empty. But atleast you wouldn't need to add many overloads and people would not use that by mistake as it will be decoupled from the usual Builder<> api.

Regards,
Torni
Reply all
Reply to author
Forward
0 new messages