1

I have 2 collections in my database. Let's say collection_1 and collection_2. I want to copy or move all of my documents in collection_1 to collection_2 using C#.

Any idea please?

maxrena
  • 501
  • 1
  • 4
  • 14

2 Answers2

4

Here's a solution to copy between databases. If they are on the same database then it is even more simple, just use one mongo client

 var fromConnectionString = "mongodb://localhost:27017"; // if copy between same database then obviously you only need one connectionstring and one MongoClient
 var toConnectionString = "mongodb://localhost:27017";
 var sourceClient = new MongoClient(fromConnectionString);
 var copyFromDb = sourceClient.GetDatabase("CopyFromDatabaseName");
 var copyCollection = copyFromDb.GetCollection<BsonDocument>("FromCollectionName").AsQueryable(); // or use the c# class in the collection
 var targetClient = new MongoClient(toConnectionString);
 var targetMongoDb = targetClient.GetDatabase("CopyToDatabase");
 var targetCollection = targetMongoDb.GetCollection<BsonDocument>("ToCollectionName");

 targetCollection.InsertMany(copyCollection);
SJFJ
  • 657
  • 6
  • 18
0

With database query. Source :https://docs.mongodb.com/manual/reference/method/db.cloneCollection/

       db.cloneCollection('mongodb.example.net:27017', 'profiles', { 'active' : true } )

With C# Source: Duplicate a mongodb collection

var source = db.GetCollection("test");
var dest = db.GetCollection("testcopy");
dest.InsertBatch(source.FindAll());
  • This pretty much identical to my answer but InsertBatch is depricated. But are you using an old driver it will work the same way. – SJFJ May 16 '19 at 06:25
  • I'm using InsertBatch, but you can use InsertMany if you're using other version. – Mehmet Ordu May 16 '19 at 06:38