mongodb - 如何在mongoDB聚合中循环数组对象并按条件重新赋值?
问题描述
我对 mongo 聚合有疑问,请帮忙。
首先,我有一个这样的集合:
{
"id": 1,
"properties": [
{
key: "prop1",
value: "propVal1",
},
{
key: "prop2",
value: "propVal2",
},
{
key: "prop3",
value: "propVal3",
}
]
还有一个像这样的 JS 对象:
const newKeyValues = [{ key: "prop1" , value: "newVal1" }, { key: "prop2" , value: "newVal2" }];
那么如何创建一个聚合管道来通过键设置新值到properties
数组?管道的预期输出是这样的:
{
"id": 1,
"properties": [
{
key: "prop1",
value: "newVal1",
},
{
key: "prop2",
value: "newVal2",
},
{
key: "prop3",
value: "propVal3",
}
]
谢谢大家。
解决方案
我想我找到了答案,需要另一个 JS 函数来映射值key
。但是查询是基于以下内容构建的:
db.collection.aggregate({
$project: {
id: "$id",
properties: {
$map: {
input: "$properties",
as: "properties",
in: {
key: "$$properties.key",
value: {
$switch: {
branches: [
{
case: {
$eq: [
"$$properties.key",
"prop1"
]
},
then: "newValue1"
},
{
case: {
$eq: [
"$$properties.key",
"prop2"
]
},
then: "newValue2"
}
],
default: "$$properties.value"
}
}
}
}
}
}
})
推荐阅读
- reactjs - 如何使用 useStateHook 一次渲染多个 setStater
- javascript - 如何根据显示尺寸缩小元素?
- join - 如何基于共享列在 Splunk 中加入 2 个表?
- php - 如何使用 PHP 在 mongoDB 中查询“大于”?
- python - Python 语音识别 - 狮身人面像
- bash - 两个 UTC 日期时间字符串之间的差异
- python - Pygame:蛇的身体需要跟随头部
- laravel - 我可以返回集合然后在 Laravel 中使用 BelongsTo 模型关系吗
- compiler-errors - 雪花错误 - 'SQL 编译错误:空 SQL 语句'
- node.js - Mongoose 查找数组包含至少一个与 id 匹配的对象的位置