简体   繁体   English

如何使用C#驱动程序将文档移动到MongoDB中的另一个数据库?

[英]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. 我从数据库A中检索所有文档,然后根据文档中的内容将它们分为2类。 (The code is done) (代码已完成)

  2. If this document belongs to Category 1, it should be move to another database in MongoDB. 如果此文档属于类别1,则应将其移至MongoDB中的另一个数据库。

  3. If this document belongs to Category 2, it should be deleted from the database. 如果此文档属于类别2,则应将其从数据库中删除。

How can I achieve step 2? 我如何实现第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. 您的过滤器变量现在包含所有已过滤的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. 并使用适当的命令将值插入到新值中,然后像在elseif情况下一样从旧数据库中删除相同的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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