我在MongoDB中有一个包含两个集合的数据库:
Collection1:
{
"id": "675",
"material_category_id": "35",
"material_name": "name",
"material_original_name": "Name",
"material_other_names": "",
"material_description": "Stuff about material",
"material_online_id": null,
"material_country_of_origin": "243",
"main_color": "9",
"page_title": "Page Title",
"pattern": "0",
"last_update": "2015-06-22 13:59:47"
}
Collection2:
{
"id": "3852",
"material_id": "675",
"material_photo_name": "stuff.jpg",
"original_name": "otherstuff.jpg",
"visible": "1",
"uploaded_at": "2015-11-16 05:27:00",
"thumb": "0"
}
我需要将“material_photo_name”从collection2转移到collection1中以获取每个相应的文档(collection2中的material_id与collection1中的id匹配)...有没有办法在不手动重写数据库的情况下执行此操作?集合2中有成千上万的文档,集合中有数百个... 注意:每个值都是唯一的,因此简单的update()将不起作用。
答案 0 :(得分:1)
您必须编写迁移脚本。
您可以使用mongo shell轻松完成。它看起来像这样:
mongo
use yourDB
db.Collection1.find().forEach(function(doc1){
var doc2 = db.Collection2.findOne({material_id: doc1.id});
doc1.material_photo_name = doc2.material_photo_name;
db.Collection1.save(doc1);
});
如果此任务是开发项目的一部分,建议使用迁移框架(例如mongo-migrate)。有各种语言的迁移框架。