I had a document like this:
const myUser = 'e'
//Collection Selection
{
level: [
{
currentUser: 'f',
stages: [
{
users: ['a','b','c']
},
{
users: ['b','d','e']
}
]
},
{
currentUser: 'g',
stages: [
{
users: ['y','x','w']
},
{
users: ['x','v','f']
}
]
}
]
}
I want to select the level
s where myUser
is in at least one of the stage
s or is the currentUser
, so I’m making a query like this:
Selection.aggregate()
.addFields({myUser})
.addFields({allUsers: { // flattening all arrays into [a,b,c,b,d,e,y,x,w,x,v,f]
$reduce: {
input: {
$reduce: {
input: $level.stages.users,
initialValue: [],
in: { $concatArrays: ['$$value', '$$this'] }
},
initialValue: [],
in: { $concatArrays: ['$$value', '$$this'] }
}
}}})
match({
$or: [
{
myUser: myUser
},
{
myUser: {$in: '$allUsers'}
}
]
})
and I don’t know why I get an
$in requires an array
error message. What am I doing wrong here?
2
Answers
I just found out doing this works as well:
Use
$expr
to compare fields in a document.Sample Mongo Playground
Mongoose