2011-01-14 86 views
16

据我所见,所有命令都在mongodb中的相同数据库上运行。我想要做这样的事情:如何将一个记录从一个mongo数据库插入另一个?

db.mySourceCollection.find()。forEach(function(x){db.theDestinationCollection.save(x)});

其中mySourceCollectionliveDatabasetheDestinationCollectiontestDatabase

回答

15

使用use :-)

> var documents = db.mySourceCollection.find() 
> use testDatabase 
switched to db testDatabase 
> documents.forEach(function(x){ db.theDestinationCollection.insert(x) }) 

db被用来指代当前连接的数据库,但是你可以使用use命令飞切换数据库,正如我上面显示。

查看shell中的help命令 - 它提到了这个命令以及更多!

+0

谢谢!我知道使用,但我不会想到坚持变量的状态。我希望在流体使用的db上有一个use()方法,例如, db.use('sourceDb')。collectionA.do(db.use('destDb')。 – b7kich 2011-01-14 18:55:43

13

use dbname不脚本模式工作(即脚本使用JavaScript shell时),所以你应该使用db.getSiblingDB()方法,而不是重新分配“DB”的变量,例如:这里

db = db.getSiblingDB("otherdb") 

更多信息:http://www.mongodb.org/display/DOCS/Scripting+the+shell

相关问题