-
Type:
Bug
-
Resolution: Works as Designed
-
Priority:
Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
-
None
-
Dotnet Drivers
-
None
-
None
-
None
-
None
-
None
-
None
Summary
MongoDB.Driver version: 2.23.1
Server version 7.0.8
I need to build a projection using $filter. The closest thing that I could find in the C# driver is projection.ElemMatch() method. This generates a Mongo query using $elemMatch and it fails at run time.
How to Reproduce
This is the handwritten Mongo query that I want to build in C#:
{ "$project": { "session_id": 1, "is_priority": 1, "document_created_on": 1, "document_created_by": 1, "reviews": { "$filter": { "input": "$reviews", "as": "reviews", "cond": { "$and": [{ "$eq": ["$$reviews.type", "MBRVW"] }, { "$or": [{ "$eq": ["$$reviews.status_code", "APPROVED"] }, { "$eq": ["$$reviews.status_code", "CONTESTED"] } ] } ] } } } } }
This is the C# code:
public static ProjectionDefinition<ProviderFeedback> CreateProjection2(FeedbackGetRequestDto request) { List<string> statusFilters = GetStatusFilters(request); var projection = Builders<ProviderFeedback>.Projection .Include(f => f.SessionId) .Include(f => f.IsPriority) .Include(f => f.DocumentCreatedOn) .Include(f => f.DocumentCreatedBy); Expression<Func<Review, bool>> filter = review => review.TypeCode == request.ReviewType && statusFilters.Contains(review.StatusCode) : projection = projection.ElemMatch(f => f.Reviews, filter); return projection; }
And this is the Mogo query that it generates:
{ "$project": { "session_id": 1, "is_priority": 1, "document_created_on": 1, "document_created_by": 1, "reviews": { "$elemMatch": { "type": "MBRVW", "status_code": { "$in": ["APPROVED", "CONTESTED"] } } } } }
This is the runtime error:
MongoDB.Driver.MongoCommandException: Command aggregate failed: Invalid $project :: caused by :: Cannot use $elemMatch in this context.
at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol.ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)
Please let me know what C# code should I use so that it generates a proper Mongo query.