在mongodb聚合中使用$ match

时间:2016-01-04 13:23:22

标签: mongodb

我的Node函数中有一个变量。

var storeId;

storeId的值可能是也可能不是undefined

现在,如果是undefined,我不希望基于此参数过滤掉$match。如果storeId有值,$match应根据storeId过滤掉。

$match: {
       type: "abc",
      "_store._id":storeId?: //something like if else here 
    }

我应该在这里添加什么?

1 个答案:

答案 0 :(得分:1)

我会通过创建一个匹配的空对象然后有条件地填充它来解决这个问题:

var match = {};
if (storeId != undefined) match.storeId = storeId;
if (type != undefined) match.type = type;
//...

然后在聚合管道中使用该对象:

 { $match: match }