1. 程式人生 > >mongoDB 邏輯運算子

mongoDB 邏輯運算子

在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:"
[email protected]
"}]}) //不同的鍵基於$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列為undefined
WriteResult({ "nInserted" : 1 })

    db.users.find({age:{$type:6}})
    { "_id" : ObjectId("57d4ed86280c7afecd0250cb"), "ename" : "fred", "age" : undefined, "add" : "SZ" }