Javascript 如果我没有';我不知道文档Id

Javascript 如果我没有';我不知道文档Id,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我的任务是使用mongo db重建一个更单一的数据库。在这个数据库中,我有一个如下所示的产品文档 { product_id: 4. questions: [ { question_id: 10, question_text: "hello?", helpfulness: 0 }, { question_id: 11, question_text: "goodbye?"

我的任务是使用mongo db重建一个更单一的数据库。在这个数据库中,我有一个如下所示的产品文档

{
  product_id: 4.
  questions: [
    {
      question_id: 10,
      question_text: "hello?",
      helpfulness: 0
    },
    {
      question_id: 11,
      question_text: "goodbye?",
      helpfulness: 1
    }
  ]
}

我将收到一个到我的服务器的请求,其中包括问题id(即11),我需要增加问题的帮助性。我到处都找过了,但我似乎找不到一种方法,只使用问题id查询我的数据库,并在不知道产品id的情况下更新该问题。有什么方法可以做到这一点吗?非常感谢你的帮助

我认为给定的查询可以帮助您获取和更新产品文档:

db.product.update({questions: {$elemMatch: {question_id:'11'}}},{
     $inc: {"questions.helpfulness": 1}
})

此处$inc用于将您的帮助值增加1

在这里,首先需要匹配问题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
        }
    ]
}