Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a Mongo Collection in PHP

Tags:

php

mongodb

PHP's Mongo driver lacks a renameCommand function. There is reference to do this through the admin database. But it seems more recent versions of the Mongo driver don't let you just "use" the admin database if do don't have login privileges on that database. So this method no longer works. I've also read this doesn't work in sharded environments although this isn't a concern for me currently.

The other suggestion people seem to have is to iterate through the "from" collection and insert into the "to" collection. With the proper WriteConcern (fire and forget) this could be fairly fast. But it still means pulling down each record over the network into the PHP process and then uploading it back over the network back into the database.

I ideally want a way to do it all server-side. Sort of like an INSERT INTO ... SELECT ... in SQL. This way it is fast, network efficient and a low load on PHP.

like image 460
Eric Anderson Avatar asked Jul 22 '13 17:07

Eric Anderson


People also ask

How do I rename a MongoDB collection?

renameCollection() method is used to rename a collection. The new name of the collection. Enclose the string in quotes. If true, mongod drops the target of renameCollection prior to renaming the collection.

Can we rename MongoDB?

The ability to rename a MongoDB database is a feature that the MongoDB team is still working on. In the meantime, there's an easy workaround that only requires a few clicks when using the MongoDB GUI, Studio 3T: Copy the original database by copying all the collections, views, and buckets in it. Create a new database.

How do I rename a view in MongoDB?

Renaming views in MongoDB is not possible yet. You have to drop the existing one and create a new one. Save this answer.

How do I change the key name in MongoDB?

MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. This operator is used to update the names of the fields with new names. The new name of the field should be different from the existing name of the field.


1 Answers

I have just tested this, it works as designed ( http://docs.mongodb.org/manual/reference/command/renameCollection/ ):

$mongo->admin->command(array('renameCollection'=>'ns.user','to'=>'ns.e'));

That is how you rename an unsharded collection. One problem with MR is that it will change the shape of the output from the original collection. As such it is not very good at copying a collection. You would be better off copying it manually if your collection is sharded.

As an added note I upgraded to 1.4.2 (which for some reason comes out from the pecl channel into phpinfo() as 1.4.3dev :S) and it still works.

like image 157
Sammaye Avatar answered Oct 23 '22 18:10

Sammaye