重命名文档数组中的子文档字段

Rename a sub-document field within an Array of an Document

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

{
"_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'} } )

但在我的案例中没有用

如官方文档中所述,$rename 不适用于数组。 请检查下面的 link: 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 = []
})