As described here from MongoDB 4.2 on it is possible to update documents with an aggregation pipeline.
It means that now it is possible to express "conditional updates based on current field values or updating one field using the value of another field(s)".
For instance:
db.members.update(
{ },
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "misc1", "misc2" ] }
],
{ multi: true }
)
My question is: how can I do this using MongoDB on C#?
The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.
By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.
MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee. When compared to the free edition, this edition has some advanced features.
IMongoCollection
's UpdateMany takes UpdateDefinition<T>
as second parameter and PipelineUpdateDefinition is one of the derived classes. There's no expression trees support so far but you can utilize BsonDocument
class:
IMongoCollection<BsonDocument> col = ...;
var pipeline = new EmptyPipelineDefinition<BsonDocument>()
.AppendStage("{ $addFields : { " +
"status : 'Modified'," +
"comments: [ '$misc1', '$misc2' ]," +
"lastUpdate: '$$NOW' " +
"} }",
BsonDocumentSerializer.Instance)
.AppendStage("{ $project : { 'misc1':0, 'misc2':0 } }",
BsonDocumentSerializer.Instance);
col.UpdateMany(new BsonDocument(), pipeline);
which executes following command (trace from MongoDB driver):
"updates" : [
{
"q" : { },
"u" : [
{ "$addFields" : { "status" : "Modified", "comments" : ["$misc1", "$misc2"], "lastUpdate" : "$$NOW" } },
{ "$project" : { "misc1" : 0, "misc2" : 0 } }],
"multi" : true }
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With