Penguen
Penguen

Reputation: 17288

How can I convert mongo script to pure C# code by using native MongoDB.Driver?

How can I convert below mongodb shell script to C# by using "MongoDB.Driver" ? the script below is working perfect in local. There is no issue in script. But if I publish it as Azure func. There is permission issue for "eval "operator. So I decided to rewrite above script as Native C# by using MongoDb.Driver.I developed below code, but "eval" didn't work and throwed error while running in Azure function: "Command eval failed: Command is not supported. ". I decided convert to pure C# code.How can I do That?


    Date.prototype.addDays = function(h) {    
   this.setTime(this.getTime() + (h*60*60*1000*24)); 
   return this;   
} 

var beforeDate = (new Date()).addDays(-7);
var totalDeleted = 0;

do
{

    var ids = db.klm
        .find({
            CreatedDate: {$lt: beforeDate},
            xyz: {$eq: null},
            abc: {$eq: null},
            Items: { $size: 0 }
        })
        .limit(100)
        .map(function (doc) { return doc._id; });

    totalDeleted += ids.length;

    //db.klm.remove({"_id": { "$in": ids }});

} while (ids.length > 0);

print("Deleted " + totalDeleted + " rows before " + beforeDate);

Upvotes: 1

Views: 804

Answers (1)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5669

the following will delete everything with the matching filter. it does not delete in batches of 100s as your shell code which would be less efficient. the following only issues a single mongodb query which would take care of deleting all matching records.

var beforeDate = DateTime.UtcNow.AddDays(-7);

var filter = Builders<klm>.Filter
                          .Where(k =>
                                 k.createdDate < beforeDate &&
                                 k.abc == null &&
                                 k.xyz == null &&
                                 (k.items.Count() == 0 || k.items == null));

var result = collection.DeleteMany(filter);

Console.WriteLine($"Deleted {result.DeletedCount} documents created before {beforeDate.ToShortDateString()}");

update: the following will result in 2 queries for each batch of 100 records.

var beforeDate = DateTime.UtcNow.AddDays(-7);
var totalDeleted = 0;
var ids = new List<ObjectId>();

do
{
    ids = collection.Find(k =>
                          k.createdDate < beforeDate &&
                          k.abc == null &&
                          k.xyz == null &&
                         (k.items.Count() == 0 || k.items == null))
                    .Limit(100)
                    .Project(k => k.Id)
                    .ToList();

    if (ids.Any())
    {
        collection.DeleteMany(k => ids.Contains(k.Id));
        totalDeleted += ids.Count();
    }               

} while (ids.Any());

Console.WriteLine($"Deleted {totalDeleted} documents created before {beforeDate.ToShortDateString()}");
Console.ReadLine();

Upvotes: 1

Related Questions