Ignore the field in the query if the field does not exist or is null?

I am using the following query:

$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;}'}
    ]

is a more elegant way to ignore a field in a request if the ist field is not set or is null? With your own mango query operators?

+4
source share
1 answer

To ignore fields that either don't exist or are null, you need to use a combination of query operators $existsand $type.

$ exists:

: {: {$ : <boolean>}}
<boolean> , $, , , , . <boolean>false, , .

$:

$type , BSON

BSON types:

Null    10
Double  1
String  2

BSON mongodb, : http://docs.mongodb.org/manual/reference/bson-types/

, mongo , vehicle.class exists, String.

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

type 2 , String type 10 null. , , . , String, null.

Double, type - 1, Numbers, 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}}]}]
})
+4

All Articles