【发布时间】:2021-05-04 10:28:04
【问题描述】:
我有一组对象称为“额外”,具有不同的属性:有些对象有“加号”,有些没有。 我想在这个“额外”数组中创建 2 个不同的数组,一个称为“cheap”,其中包含所有不具有“plus”属性的对象,另一个称为“exp”,仅包含具有“plus”属性的对象。 我想我可以将 mongodb 聚合中的 $reduce 方法与 $concatArrays 一起使用,并使用 $cond 检查属性 plus 是否存在。 类似的东西:
数据示例:
{
extra: [
{
description: "laces",
type: "exterior",
plus: '200'
},
{
description: "sole",
type: "interior"
},
{
description: "logo",
type: "exterior"
},
{
description: "stud",
type: "exterior",
plus: '450'
}
],
}
{
$project: {
extra: {
$reduce: {
input: ['$extra'],
initialValue: {cheap: [], exp: []},
$cond: {
if: {$eq: ['$$this.plus', null]},
then: {
in: {
cheap: {
$concatArrays: ['$$value.cheap', '$$this'],
},
},
},
else: {
in: {
exp: {
$concatArrays: ['$$value.exp', '$$this'],
},
},
},
},
},
},
},
}
它不起作用...我尝试了很多方法或编写 $cond 部分没有运气。 我想不通。 谢谢你们。 K.
【问题讨论】:
-
请至少提供几条关于您的收集数据的记录。
标签: javascript mongodb aggregation-framework reduce