Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver Update Document with Aggregation Pipeline

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#?

like image 640
Geraldo Neto Avatar asked May 16 '20 19:05

Geraldo Neto


People also ask

What is MongoDB C driver?

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.

Can you use MongoDB with C#?

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.

Is MongoDB free to use?

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.


1 Answers

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 }
    }
]
like image 82
mickl Avatar answered Sep 30 '22 12:09

mickl