mongodb - 无法将对象添加为另一个现有 JSON 对象的子字段
问题描述
我无法添加以下对象:
[
{ 'option1':'opt1','option2':'opt2','option3':'opt3'},
]
作为提交给:
const question_list=await Questions.find({ $and: [{categoryid:categoryId},{ isDeleted: false }, { status: 0 }] }, { name: 1 });
question_list=[{"_id":"5eb167fb222a6e11fc6fe579","name":"q1"},{"_id":"5eb1680abb913f2810774c2a","name":"q2"},{"_id":"5eb16b5686068831f07c65c3","name":"q5"}]
我希望最终的对象是:
[{"_id":"5eb167fb222a6e11fc6fe579","name":"q1","options":[
{ 'option1':'opt1','option2':'opt2','option3':'opt3'},
]},{"_id":"5eb1680abb913f2810774c2a","name":"q2","options":[
{ 'option1':'opt1','option2':'opt2','option3':'opt3'},
]},{"_id":"5eb16b5686068831f07c65c3","name":"q5","options":[
{ 'option1':'opt1','option2':'opt2','option3':'opt3'},
]}]
什么是最好的解决方案?
解决方案
您需要使用聚合管道来执行此操作,而不是.find()
. 由于投影.find()
只能接受$elemMatch, $slice, and $
现有字段:project-fields-from-query-results。因此,要在文档中添加包含新数据的新字段,请$project
在聚合框架中使用。
const question_list = await Questions.aggregate([
{
$match: {
$and: [{ categoryid: categoryId }, { isDeleted: false }, { status: 0 }]
}
},
{
$project: {
_id: 0,
name: 1,
options: [{ option1: "opt1", option2: "opt2", option3: "opt3" }]
}
}
]);
测试: mongoplayground
推荐阅读
- javascript - 如何在三元运算符中转换此代码
- python - 获取变量错误 - Mytable 和 tableName 可以在此 Python 代码中未定义。如何纠正?
- python - Python Discord Bot:如何与用户交互?
- github - 图像和 CSS 不适用于 github.io 页面
- bash - 在 bash 中,如果选择了文本,则配置快捷键 ctrl+c 用于复制,如果没有选择文本,则配置为 SIGINT
- c# - 将 RediSearch 与 NRediSearch (C#) 结合使用,如何在 i.CountyId == id || 等两个数字字段上应用 OR 子句 i.CityId == id
- javascript - 在页面重新加载之前是否存在触发事件的任何事件侦听器?
- html - 使用 CSS 伪造自定义 ol 标签
- android - 为什么我的亚马逊应用商店提交被拒绝?如何获取更多信息?
- apache-spark - 在单个生产命令中可以为 Kafka 主题生成的记录数量是否有任何限制