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
I had solved it like this
What you’re doing is wrong,
RunCommand
runs a single command (ieinsert/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
BsonDocument
s as stages. See for details@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#:
Using LINQ to build your queries is different, there is a blog post from earlier this year here that might be of interest.