Home > Mobile >  Aggregate with max and addfield using mongodb driver C#
Aggregate with max and addfield using mongodb driver C#

Time:10-20

I have a query like this in mongodb:

db.Product.aggregate([
 { $addFields: { maxSku: { $max: '$ProductVariants.FullSku' } } },
 { $group: { _id: null, value: { $max: '$maxSk' } } }
])

but how can I execute it using mongodb driver (linq) in C#?

I've tried to use db.RunCommandAsync but that's not working

var command = new JsonCommand<BsonDocument>("db.Product.aggregate([{ $addFields: { maxSku: { $max: '$ProductVariants.FullSku' } } },{ $group: { _id: null, value: { $max: '$maxSk' } } }])");
var result = await _productRepository.Database.RunCommandAsync<BsonDocument(command);

the error is

JSON reader was expecting a value but found 'db'.
at MongoDB.Bson.IO.JsonReader.ReadBsonType()...etc

CodePudding user response:

What you're doing is wrong, RunCommand runs a single command (ie insert/aggregate and etc), this has nothing common with the shell syntax you use (the shell can use own helpers that noone else implements). What you need is to run Aggregate command with raw BsonDocuments as stages. See for details

CodePudding user response:

@dododo provides the right guidance and answer.

I'm just stopping by to mention that you can use MongoDB Compass to help translate between aggregation pipelines defined in the shell to code for the drivers. Using these steps with the pipeline text from your question, the following is produced for C#:

new BsonArray
{
    new BsonDocument("$addFields", 
    new BsonDocument("maxSku", 
    new BsonDocument("$max", "$ProductVariants.FullSku"))),
    new BsonDocument("$group", 
    new BsonDocument
        {
            { "_id", BsonNull.Value }, 
            { "value", 
    new BsonDocument("$max", "$maxSk") }
        })
}

Using LINQ to build your queries is different, there is a blog post from earlier this year here that might be of interest.

  • Related