javascript - 当我不知道文档 ID 时如何使用 mongoose 查询子文档
问题描述
我的任务是使用 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 的情况下更新该问题。有没有办法做到这一点?非常感谢您的帮助!
解决方案
给你,首先你需要匹配问题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
}
]
}
推荐阅读
- matlab - 3D 曲面图 MATLAB
- r - 将 2 列中的所有唯一值收集到一个新列中
- c# - NHapi:为 QBP^Q21 消息创建 MSH 段时出现 System.TypeInitializationException
- python - 如何将此程序放入 python 函数中?
- datetime - C# asp.net core 2.2 - 获取当前日期时间 - 不准确
- c# - WCF 服务 - 防止生成
作为回应 - ios - 安全区域外的可点击按钮
- git - 是否可以有 2 个或更多同步的 Git 服务器
- authentication - 使用序列号在 Web API 中进行设备身份验证
- c# - 在DataGrid列WPF C#中显示数据库表中有多少行的COUNT