繁体   English   中英

当我不知道文档 ID 时,如何使用 mongoose 查询子文档

[英]how can I use mongoose to query a subdocument when I don't know the document Id

我的任务是使用 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 的情况下更新该问题。 有没有办法做到这一点? 非常感谢您的帮助!

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

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
        }
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM