From 755a7ea44649cc1137e415632babccef0f1aec2f Mon Sep 17 00:00:00 2001 From: Red Forks Date: Tue, 26 Jul 2011 14:41:17 +0800 Subject: [PATCH] add dropTarget arg to RenameCollection() if database has collection named with `newCollectionName', drop it before rename in atomic way. --- Driver/Core/MongoDatabase.cs | 11 ++++++++--- DriverOnlineTests/Core/MongoDatabaseTests.cs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Driver/Core/MongoDatabase.cs b/Driver/Core/MongoDatabase.cs index 87608f515b..c870722c9e 100644 --- a/Driver/Core/MongoDatabase.cs +++ b/Driver/Core/MongoDatabase.cs @@ -726,16 +726,21 @@ namespace MongoDB.Driver { /// Renames a collection on this database. /// /// The old name for the collection. - /// The new name for the collection. + /// The new name for the collection. + /// drop target collection if exist in db /// A CommandResult. public virtual CommandResult RenameCollection( string oldCollectionName, - string newCollectionName + string newCollectionName, + bool dropTarget = false ) { var command = new CommandDocument { { "renameCollection", string.Format("{0}.{1}", name, oldCollectionName) }, { "to", string.Format("{0}.{1}", name, newCollectionName) } - }; + }; + if (dropTarget) { + command.Add("dropTarget", BsonBoolean.True); + } return server.RunAdminCommand(command); } diff --git a/DriverOnlineTests/Core/MongoDatabaseTests.cs b/DriverOnlineTests/Core/MongoDatabaseTests.cs index b1da39b293..1de3ca393b 100644 --- a/DriverOnlineTests/Core/MongoDatabaseTests.cs +++ b/DriverOnlineTests/Core/MongoDatabaseTests.cs @@ -162,6 +162,24 @@ namespace MongoDB.DriverOnlineTests { Assert.IsTrue(database.CollectionExists(collectionName2)); } + [Test] + public void TestRenameCollectionDropTarget() { + const string collectionName1 = "testrenamecollection3"; + const string collectionName2 = "testrenamecollection4"; + Assert.IsFalse(database.CollectionExists(collectionName1)); + Assert.IsFalse(database.CollectionExists(collectionName2)); + + database[collectionName1].Insert(new BsonDocument()); + database[collectionName2].Insert(new BsonDocument()); + Assert.IsTrue(database.CollectionExists(collectionName1)); + Assert.True(database.CollectionExists(collectionName2)); + + Assert.Throws(typeof(MongoCommandException), () => database.RenameCollection(collectionName1, collectionName2)); + database.RenameCollection(collectionName1, collectionName2, true); + Assert.IsFalse(database.CollectionExists(collectionName1)); + Assert.IsTrue(database.CollectionExists(collectionName2)); + } + [Test] public void TestUserMethods() { var collection = database["system.users"];