Search code examples
c#mongodbmongodb-.net-driver

How to unset field for loads of documents?


I have huge table that is fully dynamic (not mapped to any POCO). It has multiple fields and one of them is named two. How can I remove this field for every document that has ArchiveId set to 1?

I have tried getting all items and then saving each but it gives me error. I suspect that db just times out or something because it's working and running since I can get records just fine afterwards.

Note that I have over 1m records and this method that I'm doing is probably very bad but I don't know any better.

Server instance localhost:27017 is no longer connected.

What I have tried

public void DeleteFieldByArchiveId(int id, string field)
{
    var collection = _db.GetCollection("items");

    collection.Find(Query.EQ("ArchiveId", id))
        .ToList()
        .ForEach(x =>
        {
            x[field] = null;
            collection.Save(x);
        });
}

EDIT (What I need)

db.items.update({ArchiveId: 1}, {$unset: {two : ""}}, {multi: true})

Basically this is what I want to achieve using C# mongo driver. I just tested this query in RoboMongo and it removed all fields from 1m database in about 20 seconds without timeouts. How can I execute this query inside C# mongo driver?


Solution

  • Here's the C# way of performing the query using the static Unset method of the Update class:

    IMongoQuery query = Query.EQ("Activity", 1);         
    UpdateBuilder ub = Update.Unset("two");
    MongoUpdateOptions options = new MongoUpdateOptions {
        Flags = UpdateFlags.Multi
    };
    var updateResults = examples.Update(query, ub, options);
    

    This results in:

    query = { "Activity" : 1 }
    update = { "$unset" : { "two" : 1 } }
    

    (The value of two in the update expression doesn't matter per the documentation).

    Full example:

    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    
    var client = new MongoClient(); // connect to localhost
    var server = client.GetServer();
    var test = server.GetDatabase("test");
    var examples = test.GetCollection("examples");
    
    var query = Query.EQ("Activity", 1);         
    var ub = Update.Unset("two");
    var options = new MongoUpdateOptions {
        Flags = UpdateFlags.Multi
    };
    var updateResults = examples.Update(query, ub, options);
    if (updateResults != null)
    {                
        Console.WriteLine(updateResults);
    }