有什么简单的方法吗?
当前回答
我会滥用mongo cli mongo doc中的连接功能。这意味着您可以启动一个或多个连接。 如果您想将客户集合从test复制到同一服务器中的test2。首先你开始mongo shell
use test
var db2 = connect('localhost:27017/test2')
执行常规查找并将前20条记录复制到test2。
db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });
或者通过某些标准进行筛选
db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });
只需将localhost更改为IP或主机名即可连接到远程服务器。我使用它将测试数据复制到测试数据库进行测试。
其他回答
您可以使用聚合框架解决您的问题
db.oldCollection.aggregate([{$out : "newCollection"}])
需要注意的是,oldCollection中的索引不会复制到newCollection中。
这里有很多正确答案。我会选择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);
});"
我通常会这样做:
use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });
在MongoDB中将一个集合(myCollection1)从一个数据库复制到另一个数据库,
**Server1:**
myHost1.com
myDbUser1
myDbPasword1
myDb1
myCollection1
outputfile:
myfile.json
**Server2:**
myHost2.com
myDbUser2
myDbPasword2
myDb2
myCollection2
你可以这样做:
mongoexport --host myHost1.com --db myDb1 -u myDbUser1 -p myDbPasword1 --collection myCollection1 --out myfile.json
然后:
mongoimport --host myHost2.com --db myDb2 -u myDbUser2 -p myDbPasword2 --collection myCollection2 --file myfile.json
另一种情况,使用CSV文件:
Server1:
myHost1.com
myDbUser1
myDbPasword1
myDb1
myCollection1
fields.txt
fieldName1
fieldName2
outputfile:
myfile.csv
Server2:
myHost2.com
myDbUser2
myDbPasword2
myDb2
myCollection2
你可以这样做:
mongoexport --host myHost1.com --db myDb1 -u myDbUser1 -p myDbPasword1 --collection myCollection1 --out myfile.csv --type=csv
在CSV文件中添加列类型(name1.decimal(),name1.string()..),然后:
mongoimport --host myHost2.com --db myDb2 -u myDbUser2 -p myDbPasword2 --collection myCollection2 --file myfile.csv --type csv --headerline --columnsHaveTypes
我会滥用mongo cli mongo doc中的连接功能。这意味着您可以启动一个或多个连接。 如果您想将客户集合从test复制到同一服务器中的test2。首先你开始mongo shell
use test
var db2 = connect('localhost:27017/test2')
执行常规查找并将前20条记录复制到test2。
db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });
或者通过某些标准进行筛选
db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });
只需将localhost更改为IP或主机名即可连接到远程服务器。我使用它将测试数据复制到测试数据库进行测试。
推荐文章
- elasticsearch vs . MongoDB用于过滤应用程序
- MongoDB记录所有查询
- MongoDB:如何找到安装的MongoDB的确切版本
- 如何使用mongoimport导入CSV文件?
- 在mongodb中存储日期/时间的最佳方法
- 如何排序mongodb与pymongo
- 如何在mongodb上导入。bson文件格式
- JSON文件的蒙古导入
- 如何删除mongodb中的数组元素?
- 修改MongoDB数据存储目录
- 在MongoDB中查找重复的记录
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 在猫鼬,我如何排序的日期?(node . js)
- 将映像存储在MongoDB数据库中
- 重复Mongo ObjectId的可能性在两个不同的集合中生成?