通过使用$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