2014-09-20 64 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

相关问题