我的users个集合数据在MongoDB中如下所示:

_id: ObjectId,
sports: [
  {
    name: 'cricket',
    history: [
      {
        from: 10,
        to: 30
      },
      {
        from: 30,
        to: 30
      }
    ]
  },
  // ... other sports as well
]

我试图查询的是在sports.history内有一个匹配元素满足以下条件的所有用户:from === to.(用户可以拥有多项运动,每项运动都有自己的历史). 我试图在查询中实现这一点,而不是让用户进入我的Express应用程序,然后在之后对他们进行过滤.

任何帮助都是非常感激的.谢谢!

推荐答案

通过使用$expr运算符,您可以使用各种数组运算符来查询集合.考虑首先将2D数组‘$sports.History’展平为$reduce:

 {
    $reduce: {
        input: "$sports.history",
        initialValue: [],
        in: { $concatArrays: [ "$$value", "$$this" ] }
    }
}

对给定条件下的降维数组进行$filter次滤波

{ $filter: {
    input: {
        $reduce: {
            input: "$sports.history",
            initialValue: [],
            in: { $concatArrays: [ "$$value", "$$this" ]
            }
        }
    },
    cond: {
        $eq: ['$$this.from', '$$this.to']
    }
} }

使用$size判断由上面的表达式得到的数组长度:

{ $size: { 
    { $filter: {
        input: {
            $reduce: {
                input: '$sports.history',
                initialValue: [],
                in: { $concatArrays: [ '$$value', '$$this' ] }
            }
        },
        cond: {
            $eq: ['$$this.from', '$$this.to']
        }
    } }
} }

如果过滤数组的长度大于零,则用户存在:

{ $gt: [
    { $size: { 
        $filter: {
            input: {
                $reduce: {
                    input: "$sports.history",
                    initialValue: [],
                    in: { $concatArrays: [ "$$value", "$$this" ] }
                }
            },
            cond: {
                $eq: ['$$this.from', '$$this.to']
            }
        }
    } },
    0
] }

总体而言,您的最终查询应该如下所示:

db.users.find({
    $expr: {
        $gt: [
            { $size: {
                $filter: {
                    input: {
                        $reduce: {
                            input: "$sports.history",
                            initialValue: [],
                            in: { $concatArrays: [ "$$value", "$$this" ] }
                        }
                    },
                    cond: {
                        $eq: ['$$this.from', '$$this.to']
                    }
                }
            } },
            0
        ]
    }
})

Mongo Playground

Javascript相关问答推荐

jQuery s data()[storage object]在vanilla JavaScript中?'

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

CheckBox作为Vue3中的一个组件

显示图—如何在图例项上添加删除线效果?

如何控制Reaction路由加载器中的错误状态?

MarkLogic-earch.suggest不返回任何值

在VS代码上一次设置多个变量格式

不协调嵌入图片

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

MUI迷你图:如何将$符号添加到MUI迷你图中的工具提示数据

正则表达式以确定给定文本是否不只包含邮箱字符串

如何在Firebase中读取对象的特定字段?

如何使pdf.js上的文本呈现为可选?

当S点击按钮时,我如何才能改变它的样式?

Select 所有输入.值

ReactJS扫描线演示:多个曲面未同时更新的问题

有没有一种方法可以在不定义任何属性的情况下使用CSS转换?

Reaction Chart.js为显示格式化日期的xax提供相同的差距

如何在拆分按钮Primeng 17中更改图标下拉菜单

文本动画在其消失之前