[英]how can I use mongoose to query a subdocument when I don't know the document Id
I have been tasked with rebuilding a more monolithic database using mongo db.我的任务是使用 mongo db 重建一个更加单一的数据库。 In this database, I have a product document which looks like this.在这个数据库中,我有一个看起来像这样的产品文档。
{
product_id: 4.
questions: [
{
question_id: 10,
question_text: "hello?",
helpfulness: 0
},
{
question_id: 11,
question_text: "goodbye?",
helpfulness: 1
}
]
}
I will receive a request to my server that includes the question_id (ie 11) and I will need to increment the question's helpfulness.我将收到对我的服务器的请求,其中包含 question_id(即 11),我需要增加问题的有用性。 I have looked everywhere, but I cant seem to find a method to query my database with only the question id and update that question without first knowing the product Id.我到处找,但我似乎无法找到一种方法来查询我的数据库,只使用问题 ID 并在不知道产品 ID 的情况下更新该问题。 Is there a way to do this?有没有办法做到这一点? thanks so much for any help!非常感谢您的帮助!
I think that given query can help you to fetch and update your product document :我认为给定的查询可以帮助您获取和更新您的产品文档:
db.product.update({questions: {$elemMatch: {question_id:'11'}}},{
$inc: {"questions.helpfulness": 1}
})
Here $inc is used to increment your helpfulness value by 1这里 $inc 用于将您的帮助值增加 1
Here you go, first you need to match the question id and then inc the relative helpfulness by 1. Do try this out给你,首先你需要匹配问题 id,然后加上 1 的相对帮助。试试这个
db.collection.updateOne({'questions.question_id' : 11}, {$inc : {"questions.$.helpfulness" : 1}})
Output :输出 :
{
"_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
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.