mongoDB 逻辑运算符

来源:互联网 发布:系统自动登录软件 编辑:程序博客网 时间:2024/05/20 14:15

在mongoDB中,逻辑运算也是较为常用的运算,这些逻辑运算通常包含与或非,取反,存在等等。本文描述mongoDB几类常用的逻辑运算符同时给出演示示例,供大家参考。

一、mongoDB中的几种逻辑运算符

    $or       逻辑或    $and      逻辑与    $not      逻辑非    $nor      逻辑or的取反    $exists   存在逻辑    $type     查询键的数据类型

二、演示逻辑运算

演示集合persons中用到的文档数据请参考:mongoDB 比较运算符

1. $or

    Syntax: { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }     db.persons.find( {$or : [{age:25},{email:"robinson.cheng@qq.com"}]})  //不同的键基于$or操作符的查询    db.persons.find( {$or:[{age:25},{age:{$eq:27}}]})                     //相同的键基于$or操作符的查询    db.persons.find( {age: {$in : [25,27]}})     //对于相同键的$or查询建议使用$in替换,如本查询替换上面的查询   

2. $and

    Syntax: { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }    db.persons.find( {$and: [{age:{$gt:25}},{age:{$lt:30}}]})    db.persons.find( {$and: [{age:{$gt:25}},{"score.c":75}]})        //嵌套文档作为$and查询条件            db.persons.find( {$and: [{age:{$gt:25}},{books:"MONGODB"}]})     //数组作为$and查询条件 

3. $not

    Syntax: { field: { $not: { <operator-expression> } } }     db.persons.find( { age: {$not : { $gt : 25 } } } )  //查询年龄不大于25对文档       

4. $nor

    Syntax: { $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }         db.persons.find( {$nor : [ {age: { $gt : 25 } } ] } )                        //单个条件的$nor    db.persons.find( {$nor : [ {age: { $gt : 25 } },{ books : "MONGODB" } ] } )  //查找age不大于25,并且书籍不包含MONGODB的文档db.persons.find( {$or : [ {age: { $gt : 25 } },{ books : "MONGODB" } ] } )   //该查询与上正好相反,为上一个查询的补集

5. $exists

    Syntax: { field: { $exists: <boolean> } }    //moongoDB中的exists通常是用于判断是否有这个键,而不是SQL中的某个列上存在某个值    db.users.insert({ename:"robin",age:25})            //创建一个新的集合    db.users.insert({ename:"henry",age:25,add:"SZ"})   //添加一个列    db.users.find()                                    //查询集合上的记录    { "_id" : ObjectId("57d4e95d280c7afecd0250c9"), "ename" : "robin", "age" : 25 }    { "_id" : ObjectId("57d4e96f280c7afecd0250ca"), "ename" : "henry", "age" : 25, "add" : "SZ" }    db.users.find( { add : { $exists : true } } )      //查询add列存在的记录    { "_id" : ObjectId("57d4e96f280c7afecd0250ca"), "ename" : "henry", "age" : 25, "add" : "SZ" }    db.users.find( { add : { $exists : false } } )     //查询add列不存在的记录    { "_id" : ObjectId("57d4e95d280c7afecd0250c9"), "ename" : "robin", "age" : 25 }     db.users.find({$and :[ { add:{ $exists:false } },{ age : 25 } ] } )  //复合条件    { "_id" : ObjectId("57d4e95d280c7afecd0250c9"), "ename" : "robin", "age" : 25 }       db.users.insert({author:"Leshami",blog:"http://blog.csdn.net/leshami"})           

6. $type //基于类型的查询

    { field: { $type: <BSON type number> | <String alias> } }    //类似于C#/Java中的typeof    db.users.insert({ename:"fred",age:undefined,add:"SZ"})   //age列为undefinedWriteResult({ "nInserted" : 1 })    db.users.find({age:{$type:6}})    { "_id" : ObjectId("57d4ed86280c7afecd0250cb"), "ename" : "fred", "age" : undefined, "add" : "SZ" }
0 0