Search code examples
c#mongodbmongodb-querymongodb-.net-driver

What would be the MongoDB C# driver equivalent of the following query using the array update operator $[<identifier>]


From https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up.S[%3Cidentifier%3E]

Given the following collection

{
   "_id" : 1,
   "grades" : [
      { "grade" : 80, "mean" : 75, "std" : 6 },
      { "grade" : 85, "mean" : 90, "std" : 4 },
      { "grade" : 85, "mean" : 85, "std" : 6 }
   ]
}
{
   "_id" : 2,
   "grades" : [
      { "grade" : 90, "mean" : 75, "std" : 6 },
      { "grade" : 87, "mean" : 90, "std" : 3 },
      { "grade" : 85, "mean" : 85, "std" : 4 }
   ]
}

and query

db.students2.update(
   { },
   { $set: { "grades.$[elem].mean" : 100 } },
   {
     multi: true,
     arrayFilters: [ { "elem.grade": { $gte: 85 } } ]
   }
)

How would I do this same query using the C# driver? At the moment I'm just running the query against the database using db.RunCommand as I couldn't see a way to convert this to C# with the current driver.


Solution

  • You can try below c# using both BsonDocument and json string option. There is no linq option.

    var filter = Builders<BsonDocument>.Filter.Empty;
    var update = Builders<BsonDocument>.Update.Set("grades.$[elem].mean", 100);
    var arrayFilter = new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("elem.grade", new BsonDocument("$gte", 85)));
    var arrayFilter = new JsonArrayFilterDefinition<BsonDocument>("{ \"elem.grade\": { $gte: 85 } }");
    var arrayFilters = new List<ArrayFilterDefinition> { arrayFilter };
    var updateOptions = new UpdateOptions();
    updateOptions.ArrayFilters = arrayFilters;
    var result = collection.UpdateOne(filter, update, updateOptions);