【问题标题】:How to update document field with reference field value?如何使用参考字段值更新文档字段?
【发布时间】: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"
    }
}

那么,我有两个问题:

  1. 如何将纯文本值设置为subscriptionName 字段? R:将 .name 添加到项目以获取平面文本

  2. 如何为当前文档设置 .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);
    }
    })

【问题讨论】:

    标签: mongodb shell


    【解决方案1】:

    试试这个:

    db.getCollection('couponredeemhistories')
       .updateMany({}, {$set: {subsidiaryName: 
                       db.getCollection('subsidiaries')
                       .findOne({"_id": ObjectId('5947fdf3ba4d070b882ff851')}, {_id: 0,name: 1}).name}})
    

    【讨论】:

    • 很好,它有效,回答了第一个问题:D(仅动态更改 id qst2 正在播出)
    • 使用 forEach 来迭代历史集合,以便您可以在迭代时引用每个文档的 _id。使用此文档:docs.mongodb.com/manual/reference/method/cursor.forEach/…
    • 谢谢你:D 它的工作原理(问题更新答案)
    猜你喜欢
    • 2019-08-14
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2019-02-26
    相关资源
    最近更新 更多