check if a field value exit in array - MongoDB

烈酒焚心 提交于 2021-01-28 06:32:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!