检查数组中是否存在字段值 - MongoDB [英] check if a field value exit in array - MongoDB

查看:67
本文介绍了检查数组中是否存在字段值 - MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MongoDB 并且我有以下人员集合模式:

I'm using MongoDB and i have the following schema of person collection:

Person {
    age: [number]
}

我想检查一个人的年龄是否存在于数组中,例如 [15, 20, 12, 0].我需要类似 $in 运算符的东西,但反过来.

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.

架构:

initiatives : {
    ressources: [
        { departement: ObjectId }
        { departement: ObjectId }
    ]
)

推荐答案

您可以使用 $expr$在:

Person.find({ $expr: { $in: [ "$age", [15, 20, 12, 0] ] } })

要比较数组,您需要 $setIntersection$size 运算符,请尝试:

to compare arrays you need $setIntersection and $size operators, try:

Person.find({
    $expr: {
        $gt: [
            {
                $size: {
                    $setIntersection: [
                        [
                        "15",
                        "a",
                        "12",
                        "0"
                        ],
                        "$age.x"
                    ]
                }
            },
            0
        ]
    }
})

这篇关于检查数组中是否存在字段值 - MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆