[CSHARP-2924] Consider adding conversion logic into a generated Project query for Aggregate when it's necessary Created: 05/Feb/20  Updated: 28/Oct/23  Resolved: 16/Feb/22

Status: Closed
Project: C# Driver
Component/s: Linq, LINQ3
Affects Version/s: None
Fix Version/s: 2.14.0

Type: New Feature Priority: Major - P3
Reporter: Dmitry Lukyanov (Inactive) Assignee: Unassigned
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
is duplicated by CSHARP-3067 $convert (aggregation) Closed
Problem/Incident
is caused by CSHARP-2908 System.FormatException. If result of... Closed
Related
Epic Link: CSHARP-3615

 Description   

This ticket is related to the user's question in CSHARP-2908.

Currently, this projection logic:

var resultProject = collection
.Aggregate()
.Project(
	el => new { DividedPopulation = ((el.Population / 23))            
})
.ToList();

will fail with FormatException, because we're trying to convert a double field from server response to int. We need to consider a convert top-level json node to the generated request, for example, to something like this (added `$toInt`):

{ $toInt : { $divide : [ ... ] } }

It's possible that this ticket will be implemented in the scope of LINQ redesign ticket CSHARP-2608



 Comments   
Comment by James Kovacs [ 16/Feb/22 ]

This issue has been fixed in the new LINQ provider (known as LINQ3), which is included in the 2.14 release. Fluent Aggregate uses the configured LINQ provider to support expressions. Adding an integer cast with LINQ3 renders a $convert to integer on the server:

var resultProject = coll
    .Aggregate()
    .Project(
        el => new { DividedPopulation = (int)(el.Salary / 23) });

The resulting MQL is:

aggregate([{ "$project" : { "DividedPopulation" : { "$convert" : { "input" : { "$divide" : ["$Salary", 23] }, "to" : "int" } }, "_id" : 0 } }])

Configure your MongoClientSettings to use LinqProvider.V3 if you want to use this functionality.

To configure a client to use the LINQ3 provider use code like the following

var connectionString = "mongodb://localhost";
var clientSettings = MongoClientSettings.FromConnectionString(connectionString);
clientSettings.LinqProvider = LinqProvider.V3;
var client = new MongoClient(clientSettings);

Generated at Wed Feb 07 21:43:52 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.