如何在mongodb中使用$减去$ inc的文档

问题描述 投票:0回答:1

有人能说清楚这指的是什么吗?

db.getCollection("test_index").update({ "_id" : ObjectId("5c494913d5cddcf38e8b45dd")},
{
    $inc : {'user.$.quantity_export' : {'$subtract' : ['$user.quantity_export','$user.quantity_remain']}},
    $set : {'user.$.quantity_remain' : 5}
}

)

“writeError”:{“code”:14,“errmsg”:“不能使用非数字参数递增:{user。$。quantity_export:{$ subtract:[\”$ user.quantity_export \“,\”$ user。 quantity_remain \“]}}”}

mongodb mongodb-query
1个回答
0
投票

你得到错误,因为你不能在$subtract或mazo的update方法中使用find,它应该只在Aggregation中使用,所以使用subtract查看下面的查询

db.test_index.find({"_id" : ObjectId("5c6017b31765cd7b27eb473a")}, {"abc" : {$subtract : ["$user.quantity_export","$user.quantity_remain"]} } )

它会产生以下类型的错误:

Error: error: {
    "ok" : 0,
    "errmsg" : "Unsupported projection option: abc: { $subtract: [ \"$user.quantity_export\", \"$user.quantity_remain\" ] }",
    "code" : 2,
    "codeName" : "BadValue"
}

并且这个值将放在你的$inc'user.$.quantity_export'字段,即$inc : {'user.$.quantity_export' : {'$subtract' : ['$user.quantity_export','$user.quantity_remain']}}这导致错误。您只需通过以下查询验证您获得的错误:

> db.test_index.update({"_id" : ObjectId("5c6017b31765cd7b27eb473a")}, {$inc : {"user.quantity_export" : {"Bad values" : "abc"} }} )
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 14,
        "errmsg" : "Cannot increment with non-numeric argument: {user.quantity_export: { Bad values: \"abc\" }}"
    }
})
> 

现在解决您的问题的方法是:

由于$subtract用于Aggregation,因此您必须使用聚合并在聚合的最后阶段使用$out运算符更新字段,有关更多详细信息,您可以查看aggregation pipeline的官方文档

为了您的信息,此ans中的第一个查询与$subtract产生错误,但将与聚合一起使用:

> db.test_index.aggregate([ {$match: {"_id" : ObjectId("5c6017b31765cd7b27eb473a")}}, {$project: {"abc" : {$subtract : ["$user.quantity_export","$user.quantity_remain"]} } } ])
{ "_id" : ObjectId("5c6017b31765cd7b27eb473a"), "abc" : -10000 }
© www.soinside.com 2019 - 2024. All rights reserved.