$or是一個邏輯or操作符操作在一個數據或者多個表達式並且需要選擇至少一個滿足條件的表達式,$or有至少以下表達式:
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
考慮下面的例子:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
上面的例子會查詢集合inventory中所有字段quantity小於20或者price等於10的所有文檔。
使用$or條件評估條款,MongoDB會掃描整個文檔集合,如果所有的條件支持索引,MongoDB進行索引掃描,因此MongoDB使用索引執行$or表達式,$or中的所有表達式必須支持索引,否則的話MongoDB就會掃描整個集合。
當使用$or查詢並且使用索引時,每個$or的條件表達式都可以使用自己的索引,考慮下面的查詢:
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
支持上面的查詢你不需要創建一個符合索引,而是在字段quantity上創建一個索引,在price上創建一個索引。
db.inventory.createIndex( { quantity: 1 } ) db.inventory.createIndex( { price: 1 } )
$or和sort()操作
當使用$or執行sort()查詢時,MongoDB可以使用支持$or查詢條件的索引。之前的版本不支持索引。
$or與$in
使用$or操作比較字段的值是否等於某個值時可以使用$in替換$or操作;例如查詢集合inventory中字段quantity的值等於20或者50的所有文檔,使用$in操作:
db.inventory.find ( { quantity: { $in: [20, 50] } } )
$and邏輯表達式
語法:{ $and: [ { <expression1> }, { <expression2> } , ... , {<expressionN> } ] }
$and執行一個邏輯and操作在一個或者多個表達式上,並且查詢數組中指定的所有表達式指定的文檔document,$and使用短路求值,如果第一個表達式的結果是false,MongoDB將不會執行剩余的表達式;
例如:and查詢指定同一個字段的多個查詢條件
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
這個查詢會選擇集合inventory中的所有文檔,條件是price不等於1.99並且price字段存在;
以上查詢還可以使用隱式AND操作,如下:
db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
AND查詢使用多個表達式指定相同的操作:
db.inventory.find( { $and : [ { $or : [ { price : 0.99 }, { price : 1.99 } ] }, { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } ] } )
以上字段將會查詢price字段值等於0.99或1.99並且sale字段值為true或者qty小於20的所有文檔;
使用隱式AND操作無法構建此查詢,因為它不止一次使用$or操作;
$not
語法: { field: { $not: { <operator-expression> } } }
$not執行一個邏輯not操作在指定的表達式並查詢到不匹配表達式的文檔,這包含不包括字段的文檔;
考慮如下操作:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
此查詢將會查詢inventory集合中的文檔,條件如下:price字段小於等於1.99或者price不存在。
{ $not: { $gt: 1.99 } } 不同於$lte操作,{ $lte: 1.99 }操作只會返回price字段存在並且小於等於1.99的字段。
記住$not操作符只會影響其他操作符不能獨立檢查字段和文檔,因此使用$not做邏輯析取和$ne操作測試字段內容;
使用$not操作時考慮如下操作:
操作$not操作符和其它操作符一致但是會產生一些意想不到的結果,比如數組之類的數據類型;
$not操作符不支持$regex正則表達式操作,使用//或者你的驅動接口代替,使用語言的正則表達式功能創建正則表達式對象;
考慮下面的例子使用模式匹配//:
db.inventory.find( { item: { $not: /^p.*/ } } )
此查詢將會查詢inventory集合中item字段不是以p開頭的所有文檔;
$nor
{ $nor: [ { <expression1> }, { <expression2> }, ... { <expressionN> } ] }
考慮如下操作:
db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ] } )
查詢返回所有的文檔,條件是:
包含字段price值不等於1.99,包含字段sale值不等於true,或者包含字段price值不等於1.99,不包含字段sale;或者不包含字段price,包含字段sale值不等於true;或者不包含字段price,不包含字段sale;
$nor額外比較
考慮入校操作:
db.inventory.find( { $nor: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] }
inventory集合查詢所有的文檔,條件如下:
字段price不等於1.99,字段qty不小於20,字段sale不等於true;查詢的結果包含不存在的字段;
原文:https://blog.csdn.net/yaomingyang/article/details/75103480