2014-09-20 99 views
4

我使用下面的查詢:如果字段不存在或爲空,則忽略查詢中的字段?

$and : [ 
     {$where : 'function(){if(this.vehicle.class){return this.vehicle.class == "Car";};return true;}'}, 
     {$where : 'function(){if(this.vehicle.make){return this.vehicle.make == "MERCEDES-BENZ";};return true;}'}, 
     {$where : 'function(){if(this.vehicle.model){return this.vehicle.model == "320";};return true;}'}, 
     {$where : 'function(){if(this.price && this.price.min){return this.price.min >= 1000;};return true;}'}, 
     {$where : 'function(){if(this.price && this.price.max){return this.price.max <= 1000;};return true;}'} 
    ] 

是忽略字段查詢如果不設置字段IST更優雅的方式或爲空?使用本地mongo查詢運算符?

回答

4

要忽略不存在或爲空的字段,您需要使用組合$exists$type查詢運算符。

$存在:

語法:{字段:{$存在:<boolean>}}
<boolean>是真實的,$存在包含 領域的文件相匹配,包括在字段值爲文件空值。如果<boolean> 爲false,則查詢僅返回不包含 字段的文檔。

$類型:

$類型選擇文件,其中字段的值是 指定BSON類型

BSON types: 

Null 10 
Double 1 
String 2 

要查看所有有效BSON類型的MongoDB是指:http://docs.mongodb.org/manual/reference/bson-types/

例如下面的mongo查詢將獲取那些文件的字段vehicle.classexists並且包含dat一種是String

db.collection.find({"vehicle.class":{$exists:true,$type:2}}) 

type 2凡表示,字符串和type 10表示null。我們希望找到存儲在vehicle.class中的數據類型(如果存在)的記錄是String,而不是null

對於Doubletype1,默認情況下,存儲在mongodb中的數字的數據類型是'Double'。

db.collection.find({"price.max":{$exists:true,$type:1}}) 

要輸出可以如下,使用的$and$or的組合與$exists$type來獲得。

db.collection.find({ 
$and:[{$or:[{"price.max":{$lte:1000}},{"price.max":{$exists:false}},{"price.max":{$type:10}}]}, 
{$or:[{"price.min":{$gte:1000}},{"price.min":{$exists:false}},{"price.min":{$type:10}}]}, 
{$or:[{"vehicle.model":{$in:["320"]}},{"vehicle.model":{$exists:false}},{"vehicle.model":{$type:10}}]}, 
{$or:[{"vehicle.make":{$in:["MERCEDES-BENZ"]}},{"vehicle.make":{$exists:false}},{"vehicle.make":{$type:10}}]}, 
{$or:[{"vehicle.class":{$in:["Car"]}},{"vehicle.class":{$exists:false}},{"vehicle.class":{$type:10}}]}] 
}) 
+0

「vehicle.model」:{$存在:真,$類型:2,$於:[ 「320」]} 將現場如果鍵完全不存在被忽略? – dima 2014-09-21 14:50:30

+0

偉大的答案,但它有antoher效果不像我上面寫在問題中的代碼。如果該字段不存在,則根本不能在查詢條件中使用它。 – dima 2014-09-21 14:51:48

+1

@dima - 修改了我的答案,使其更具體。 – BatScream 2014-09-21 16:59:42

相關問題