简体   繁体   中英

How to move document to another database in MongoDB using C# driver?

Here's what I want to do:

  1. I retrieve all the documents from the Database A, then I divided them into 2 categories based on its content in the documents. (The code is done)

  2. If this document belongs to Category 1, it should be move to another database in MongoDB.

  3. If this document belongs to Category 2, it should be deleted from the database.

How can I achieve step 2? Here is my code so far:

if (Answer == "Yes")
{
    MongoClient mclient = new MongoClient();
    var mdatabase = mclient.GetDatabase("Data");
    var mcollection = mdatabase.GetCollection<BsonDocument>("Sample1");
    var filter = Builders<BsonDocument>.Filter.Eq("Answer", data);
    //Data variable is consist of the Answer string    
    //How to move this document into another database?
}
else if (Answer == "No")
{
    MongoClient mclient = new MongoClient();
    var mdatabase = mclient.GetDatabase("Data");
    var mcollection = mdatabase.GetCollection<BsonDocument>("Sample1");
    var filter = Builders<BsonDocument>.Filter.Eq("Answer", data);
    var result = await mcollection.DeleteManyAsync(filter);
}

Thanks if anyone could help! I've stuck at here for many days.

Your filter variable now containing all the filtered BsonDocuments. So you can open new db connection

var newDatabase= mclient.GetDatabase("newdb");

and insert the values to the new one using appropriate Commands, and delete the same content from old database like you did in your elseif case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM