Python社区  »  MongoDB

如何有条件地在MongoDB集合中的所有子文档上设置新字段

user8888 • 2 年前 • 531 次点击  

const schema = new mongoose.Schema({
    reputationHistory: [ reputationHistorySchema ],
});

const reputationHistorySchema = new mongoose.Schema({
    isBid: { type: Boolean, default: false, required: true },
    isResult: { type: Boolean, default: false, required: true },
});

这是它的一个例子:

[{
    reputationHistory: [{
        isBid: true,
        isResult: false,
    }, {
        isBid: false,
        isResult: true,
    }]
}, {
    reputationHistory: [{
        isBid: true,
        isResult: false,
    }, {
        isBid: false,
        isResult: true,
    }]
}]

isBid == true ,那么我想要 reason 是“预言”。否则, 原因

[{
    reputationHistory: [{
        isBid: true,
        isResult: false,
        reason: "Prediction",
    }, {
        isBid: false,
        isResult: true,
        reason: "Result",
    }]
}, {
    reputationHistory: [{
        isBid: true,
        isResult: false,
        reason: "Prediction",
    }, {
        isBid: false,
        isResult: true,
        reason: "Result",
    }]
}]

以下是我的尝试:

db.users.update(
    {},
    {
        $set: {
            "reputationHistory.$[].reason": {
                $cond: { if: { "reputationHistory.$[].isBid": true }, then: "Prediction", else: "Result" }
            }   
        }

    },
    { multi: true }
)

下面是我收到的错误:

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16837,
        "errmsg" : "cannot use the part (reputationHistory of reputationHistory.$[].reason) to traverse the element ({reputationHistory: [ { isBid: true, isResult: false, _id: ObjectId('5e55042c097bca0004647e18') } ]})"
    }
})

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55618
 
531 次点击  
分享到微博
文章 [ 1 ]  |  最新文章 2 年前
mickl
Reply   •   1 楼
mickl    2 年前

MongoDB 4.2 Updates with Aggregation Pipeline ,请尝试:

db.users.updateMany({}, [ 
    { 
        $addFields: { 
            reputationHistory: { 
                $map: { 
                    input: "$reputationHistory",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { reason: { $cond: { if: { $eq: [ "$$this.isBid", true ] }, then: "Prediction", else: "Result" } } }
                        ]
                    }
                } 
            } 
        } 
    } 
])

如果你不能升级你可以使用的 $out

db.users.aggregate([ 
    { 
        $addFields: { 
            reputationHistory: { 
                $map: { 
                    input: "$reputationHistory",
                    in: { 
                        reason: { $cond: { if: { $eq: [ "$$this.isBid", true ] }, then: "Prediction", else: "Result" } },
                        isBid: "$$this.isBid",
                        isResult: "$$this.isResult"
                    }
                } 
            } 
        } 
    },
    {
        $out: "users"
    } 
])