Using $expr operator, you can go about this using various array operators to query the collection. Consider first flattening the 2D array '$sports.history' with $reduce:
{
$reduce: {
input: "$sports.history",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
}
and filtering the reduced array on the given condition with $filter
{ $filter: {
input: {
$reduce: {
input: "$sports.history",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this" ]
}
}
},
cond: {
$eq: ['$$this.from', '$$this.to']
}
} }
Check the length of the array resulting from the above expression using $size:
{ $size: {
{ $filter: {
input: {
$reduce: {
input: '$sports.history',
initialValue: [],
in: { $concatArrays: [ '$$value', '$$this' ] }
}
},
cond: {
$eq: ['$$this.from', '$$this.to']
}
} }
} }
If length of filtered array is greater than zero, then the user exists:
{ $gt: [
{ $size: {
$filter: {
input: {
$reduce: {
input: "$sports.history",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
},
cond: {
$eq: ['$$this.from', '$$this.to']
}
}
} },
0
] }
Overall your final query should look like this:
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