maxrena
maxrena

Reputation: 561

I want to copy documents from one collection to another

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?

Upvotes: 1

Views: 2010

Answers (2)

Mehmet Ordu
Mehmet Ordu

Reputation: 53

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());

Upvotes: 0

SJFJ
SJFJ

Reputation: 667

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);

Upvotes: 4

Related Questions