【问题标题】:Rename a sub-document field within an Array of an Document重命名文档数组中的子文档字段
【发布时间】:2020-05-09 18:04:06
【问题描述】:

我正在尝试重命名 MONGODB 中集合数组中的特定子字段

{
"_id" : Id("248NSAJKH258"),
"isGoogled" : true,
"toCrawled" : true,
"result" : [ 
    {
        "resultsId" : 1,
        "title" : "Text Data to be writen",
        "googleRanking" : 1,
        "isrelated" : false
    }, 
    {
        "resultId" : 2,
        "title" : "Text Data",
        "googleRanking" : 2,
        "isrelated" : true
    }]

**我需要将集合文档中的“isrelated”重命名为“related”** 使用 mongo 4.0 版

我试过了:

db.collection_name.update({}, { $rename: { 'result.isrelated': 'result.related'} } )

但在我的情况下它不起作用

【问题讨论】:

    标签: database mongodb nosql robo3t


    【解决方案1】:

    正如官方文档中提到的,$rename 不适用于数组。 请检查以下链接: https://docs.mongodb.com/manual/reference/operator/update/rename/

    但是你可以这样做

    let newResult = [];
    
    db.aa1.find({}).forEach(doc => {
        for (let i in doc.result) {
            newResult.push({
                "resultsId" : doc.result[i]['resultsId'],
                "title" : doc.result[i]['title'],
                "googleRanking" : doc.result[i]['googleRanking'],
                "related" : doc.result[i]['isrelated'],
            })
        }
    
        db.aa1.updateOne({_id: doc._id}, {$set: {result: newResult}});
        newResult = []
    })
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2011-08-31
      • 1970-01-01
      • 2012-03-04
      • 2023-04-05
      相关资源
      最近更新 更多