skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

    I had solved it like this

    var bson = await _productRepository.Collection.Aggregate()
                     .AppendStage<BsonDocument>(BsonDocument.Parse(" { $addFields: { maxSku: { $max: "$ProductVariants.FullSku" } } }"))
                     .AppendStage<BsonDocument>(BsonDocument.Parse("{ $group: { _id: null, value: { $max: "$maxSku" } } }"))
                    .FirstOrDefaultAsync();
    

  2. 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

    Login or Signup to reply.
  3. @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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search