有什么简单的方法吗?


当前回答

在我的例子中,我必须在新集合中使用旧集合中的属性子集。因此,我最终在对新集合调用insert时选择了这些属性。

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

其他回答

从现有的MongoDB atlas cluster DB导入数据最简单的方法是使用MongoDB & mongorestore命令。

要从现有的DB中创建转储,您可以使用:

mongodump --uri="<connection-uri>"

还有其他连接选项,可以在这里查找:https://www.mongodb.com/docs/database-tools/mongodump/

在dump/目录中成功创建转储后,您可以使用导入数据到您的其他db,如下所示:

mongorestore --uri="<connection-uri-of-other-db>" <dump-file-location>

类似地,对于mongorestore,还有其他连接选项,可以在命令中查找以恢复特定的集合: https://www.mongodb.com/docs/database-tools/mongorestore/

转储文件的位置将在转储目录中。可能存在与您转储的DB名称相同的子目录。例如,如果您转储了测试数据库,那么转储文件的位置将是/dump/test

这可以使用Mongo的db来完成。copyDatabase方法:

db.copyDatabase(fromdb, todb, fromhost, username, password)

参考:http://docs.mongodb.org/manual/reference/method/db.copyDatabase/

实际上,有一个命令用于将集合从一个数据库移动到另一个数据库。它只是不叫“移动”或“复制”。

若要复制集合,可以在同一数据库上克隆它,然后移动克隆的集合。

克隆:

> use db1
switched to db db1

> db.source_collection.find().forEach(
      function(x){
          db.collection_copy.insert(x)
      }
  );

移动:

> use admin
switched to db admin

> db.runCommand(
      {
          renameCollection: 'db1.source_collection',
          to              : 'db2.target_collection'
      }
  );

其他答案更适合复制集合,但如果您希望移动集合,这个答案尤其有用。

这里有很多正确答案。我会选择mongodump和mongorestore作为一个大的收藏:

mongodump --db fromDB --gzip --archive | mongorestore --drop --gzip --archive --nsFrom "fromDB.collectionName" --nsTo "toDB.collectionName"

虽然如果我想快速复制,它很慢,但它是有效的:

use fromDB 
db.collectionName.find().forEach(function(x){
   db.getSiblingDB('toDB')['collectionName'].insert(x);
});"

使用“Studio3T for MongoDB” 通过单击数据库,集合或特定的集合具有导出和导入工具 下载链接:https://studio3t.com/download/