0
votes

How do I convert this SQL to MongoDB query using C# Driver

UPDATE  dbo.MyTable SET ConcatField = CONCAT(Field1, Field2, Field3, Field4, Field5)
WHERE Id = 21 

Using MongoDB.Driver 2.2.3.3

I need MongoDB query using BsonDocument type, I don't have Strong types for my Mongo Collections as Collection is not based on fixed schema.

Trying something like this

var items = myCollection.FindSync(filter).ToList();
                foreach (var item in items)
                {
                    UpdateDefinition<BsonDocument> updateDefinition =
                        new BsonDocumentUpdateDefinition<BsonDocument>(item.Merge(ListOfStrinForSelectedFields.ToBsonDocument()));
                    myCollection.UpdateManyAsync(filter, updateDefinition);
                }
1

1 Answers

0
votes

This will be my Shell Script

var cursor = db.MyCollection.find({ "Id": 21 }), // Or what ever your find conditions is 
    bulkUpdateOps = [];

cursor.forEach(function(doc){ 
    var ConcatField = doc.Field1 + doc.Field2 + doc.Field3 ;
    bulkUpdateOps.push({ 
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "MyConCatField": ConcatField  } }
         }
    });

    if (bulkUpdateOps.length == 1000) {
        db.MyCollection.bulkWrite(bulkUpdateOps);
        bulkUpdateOps = [];
    }
});         

if (bulkUpdateOps.length > 0) { db.MyCollection.bulkWrite(bulkUpdateOps); }

then execute it in c# with RunCommandAsync method from MongoDatabase.

var result = await mongoDatabase.RunCommandAsync<BsonDocument>(BsonDocument.Parse(command));

Note: you will have to modify the command string using pipelines and parse it to BsonDocument.