MongoDB——查询条件和选择器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhc2207221755/article/details/88929440

范围

>,< ,>=, <=:

查询numIndex>50 && numIndex<55:

db.getCollection('student').find({numIndex:{"$gt":50,"$lt":55}})

结果:

/* 1 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c667"),
    "numIndex" : 51.0
}

/* 2 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c668"),
    "numIndex" : 52.0
}

/* 3 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c669"),
    "numIndex" : 53.0
}

/* 4 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c66a"),
    "numIndex" : 54.0
}

同样,查询numIndex>=50 && numIndex<=55:

db.getCollection('student').find({numIndex:{"$gte":50,"$lte":55}})

设置运算符

$in: 如果任意参数在引用集合里面,则匹配
$nin:如果任意参数不在引用集合里面,则匹配
$all:如果所有参数在引用集合里且被使用在 包含数组的文档中,则匹配

in示例:

db.getCollection('student').find({numIndex:{"$in":[50,51]}})

返回:

/* 1 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c666"),
    "numIndex" : 50.0
}

/* 2 */
{
    "_id" : ObjectId("5ca0539659aa1df98e31c667"),
    "numIndex" : 51.0
}

nin示例:

db.getCollection('student').find({numIndex:{"$nin":[50,51]}}).count()  //返回:29998

all示例:
对于数据:

{
    "_id" : ObjectId("5b6068cf4b008f4e969ef4fe"),
    "name" : "aaa",
    "age" : 10.0,
    "favourite" : [ 
        "pie", 
        "apple", 
        "candy", 
        "ice cream"
    ]
}
。。。。。。。

查询:

db.getCollection('user').find({favourite:{'$all':["pie","apple"]}})

可以匹配到favourite包含pie和apple的这条。

需要注意的是: i n , in , all在有索引的前提下,是使用索引的;而$nin使用时候则需要注意,如果不是搭配别的索引搜索方式,是全部搜索的。

扫描二维码关注公众号,回复: 5726786 查看本文章

布尔运算符

符号 描述
$ne 不匹配参数调节
$not 不匹配结果
$or 有一个条件匹配则成立
$nor 所有条件都不匹配
$and 所有条件都匹配
$exists 判断元素是否存在
db.getCollection('student').find({numIndex:{"$not":{"$gt":20}}}).count()  // =>21 
//其他类似。。。
db.getCollection('user').find({favourite:{'$exists':true}}) //查询包含favourite属性的数据

对于数组

符号 描述
$elemMatch 如果提供的所有词语,在相同的子文档中,则匹配
$size 根据数组大小匹配

对于数据:

{
    "_id" : ObjectId("5b6068cf4b008f4e969ef4fe"),
    "name" : "aaa",
    "age" : 10.0,
    "favourite" : [ 
        "pie", 
        "apple", 
        "candy", 
        "ice cream"
    ],
    "address" : [ 
        {
            "code" : 10010.0,
            "name" : "望京soho"
        }, 
        {
            "code" : 10011.0,
            "name" : "moto"
        }, 
        {
            "code" : 10012.0,
            "name" : "朝外soho"
        }
    ]
}
db.getCollection('user').find({"address":{$elemMatch:{"name":"望京soho"}}})
//等价于:db.getCollection('user').find({"address.name":"望京soho"})

elemMatch可以匹配多个或者更多属性的子文档;

size:

db.getCollection('user').find({"address":{$size:3}})

JavaScript查询运算符

例如:

db.getCollection('user').find({"$where": 'return this.age > 10'})

其中where后面可以跟着一个function.

#使用正则表达式

db.getCollection('user').find({"name": {"$regex":"b"}})

其他

符号 描述
$mod 如果元素除以除数符合结果则匹配
$type 如果元素符合指定的BSON类型则匹配
$text 允许在建立文本索引的基础上执行文本搜索

猜你喜欢

转载自blog.csdn.net/lhc2207221755/article/details/88929440