问题
I'm using MongoDB and i have the following schema of person collection:
Person {
age: [number]
}
i want to check if the age of a person exist in array, for exemple [15, 20, 12, 0]. i need something like $in operator but in reverse.
schema:
initiatives : {
ressources: [
{ departement: ObjectId }
{ departement: ObjectId }
]
)
回答1:
You can use $expr with $in:
Person.find({ $expr: { $in: [ "$age", [15, 20, 12, 0] ] } })
EDIT: to compare arrays you need $setIntersection and $size operators, try:
Person.find({
$expr: {
$gt: [
{
$size: {
$setIntersection: [
[
"15",
"a",
"12",
"0"
],
"$age.x"
]
}
},
0
]
}
})
来源:https://stackoverflow.com/questions/55106243/check-if-a-field-value-exit-in-array-mongodb