【发布时间】:2017-06-26 14:36:29
【问题描述】:
实际上有 2 个文件:Histories 和 Subsidiaries,但我忘记在 Histories 中添加子公司名称。
历史文档:
{
"_id" : ObjectId("59480f91ba4d070b882ff924"),
"subsidiary" : ObjectId("5947fdf3ba4d070b882ff851"),
"campaignTitle" : "Prueba Autoredeeem",
"campaignId" : ObjectId("5948004fba4d070b882ff886"),
}
附属文件
{
"_id" : ObjectId("5947fdf3ba4d070b882ff851"),
"loginId" : 50174,
"name" : "Sucursal Alpha",
}
现在我需要更新History Document,从Subsidiary Document中添加一个带有“Subsidiary.name”值的“subsidiaryName”字段
这是我的第一个方法:
db.getCollection('couponredeemhistories')
.updateMany({}, {$set: {subsidiaryName:
db.getCollection('subsidiaries')
.findOne({"_id": ObjectId('5947fdf3ba4d070b882ff851')}, {_id: 0,name: 1})}})
但是,结果给了我一个在 subnamedName 中的对象,而不是纯文本。
{
"_id" : ObjectId("59480f91ba4d070b882ff924"),
"subsidiary" : ObjectId("5947fdf3ba4d070b882ff851"),
"campaignDescription" : "",
"campaignTitle" : "Prueba Autoredeeem",
"campaignId" : ObjectId("5948004fba4d070b882ff886"),
"subsidiaryName" : {
"name" : "Sucursal Alpha"
}
}
那么,我有两个问题:
如何将纯文本值设置为subscriptionName 字段?R:将 .name 添加到项目以获取平面文本如何为当前文档设置 .findOne() "id" 参数而不是 ObjectId('HARD CODE')?R:使用 forEach 游标进行迭代
重要限制:这是针对 MongoDB Shell (MongoDB 3.4)
谢谢,请支持我解决这个问题的任何语言问题。
感谢@Astro 更新了答案:
db.getCollection('couponredeemhistories').find()
.forEach(function(doc){
if(doc.subsidiary !== undefined){
doc.subsidiaryName = db.getCollection('subsidiaries').findOne({'_id': doc.subsidiary}, {_id: 0, name: 1}).name;
db.getCollection('couponredeemhistories').save(doc);
}
})
【问题讨论】: