Actually have 2 documents: Histories and Subsidiaries, but I forgot add to Histories the subsidiary name.
Histories Document:
{
"_id" : ObjectId("59480f91ba4d070b882ff924"),
"subsidiary" : ObjectId("5947fdf3ba4d070b882ff851"),
"campaignTitle" : "Prueba Autoredeeem",
"campaignId" : ObjectId("5948004fba4d070b882ff886"),
}
Subsidiary Document
{
"_id" : ObjectId("5947fdf3ba4d070b882ff851"),
"loginId" : 50174,
"name" : "Sucursal Alpha",
}
Now I need update History Document , add a "subsidiaryName" field with "Subsidiary.name" value from Subsidiary Document
This is my first aproach:
db.getCollection('couponredeemhistories')
.updateMany({}, {$set: {subsidiaryName:
db.getCollection('subsidiaries')
.findOne({"_id": ObjectId('5947fdf3ba4d070b882ff851')}, {_id: 0,name: 1})}})
But, the result gives me an Object inside subsidiaryName, instead flat text.
{
"_id" : ObjectId("59480f91ba4d070b882ff924"),
"subsidiary" : ObjectId("5947fdf3ba4d070b882ff851"),
"campaignDescription" : "",
"campaignTitle" : "Prueba Autoredeeem",
"campaignId" : ObjectId("5948004fba4d070b882ff886"),
"subsidiaryName" : {
"name" : "Sucursal Alpha"
}
}
Then, I have 2 problems:
How to set only flat text value to subsidiaryName field?
R: Add .name to project for get flat text
How to set .findOne() "id" param for current document instead ObjectId('HARD CODE')?
R: Iterate with forEach Cursor
IMPORTANT LIMITS: this is for MongoDB Shell (MongoDB 3.4)
Thank you, please support me for fix any language issues on this question.
Updated Answers thanks to @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);
}
})
Try this:
db.getCollection('couponredeemhistories')
.updateMany({}, {$set: {subsidiaryName:
db.getCollection('subsidiaries')
.findOne({"_id": ObjectId('5947fdf3ba4d070b882ff851')}, {_id: 0,name: 1}).name}})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.