我的任务是使用mongo db重建一个更完整的数据库。在这个数据库中,我有一个产品文档,看起来像这样。
{
product_id: 4.
questions: [
{
question_id: 10,
question_text: "hello?",
helpfulness: 0
},
{
question_id: 11,
question_text: "goodbye?",
helpfulness: 1
}
]
}我将收到对我的服务器的请求,其中包含question_id (即11),并且我将需要增加问题的有用性。我已经到处找过了,但我似乎找不到一种方法来查询我的数据库,只使用问题Id并在不首先知道产品id的情况下更新该问题。有没有办法做到这一点?非常感谢你的帮助!
发布于 2020-10-16 11:42:35
我认为给定的查询可以帮助您获取和更新产品文档:
db.product.update({questions: {$elemMatch: {question_id:'11'}}},{
$inc: {"questions.helpfulness": 1}
})这里使用$inc将您的有帮助性值增加1
发布于 2020-10-16 12:15:03
在这里,首先您需要匹配问题id,然后将相对帮助值加1。
db.collection.updateOne({'questions.question_id' : 11}, {$inc : {"questions.$.helpfulness" : 1}})输出:
{
"_id" : ObjectId("5f891ca72857d128c68bf01a"),
"product_id" : 4.0,
"questions" : [
{
"question_id" : 10.0,
"question_text" : "hello?",
"helpfulness" : 0.0
},
{
"question_id" : 11.0,
"question_text" : "goodbye?",
"helpfulness" : 2.0
}
]
}https://stackoverflow.com/questions/64382174
复制相似问题