2017-07-17 108 views
0

我想构建一个匹配其中包含数据的字段的查询。动态构建聚合查询的json结构

我尝试这样做:

var matchStr = {}; 
if (received.user) { 
    matchStr = { "_id": { "$regex": received.user, "$options": "i" } }; 
} 
if (received.name) { 
    matchStr += { "name": { "$regex": received.name, "$options": "i" } }; 
} 
if (received.phone) { 
    matchStr += { "phone": { "$regex": received.phone, "$options": "i" } }; 
} 

usersTable.aggregate([ 
{ 
    $match: { matchStr } 
}, etc... 

我尝试这样做:

var matchStr = []; 
if (received.user) { 
    matchStr.push({ "_id": { "$regex": received.user, "$options": "i" } }); 
} 
if (received.name) { 
    matchStr.push({ "name": { "$regex": received.name, "$options": "i" } }); 
} 
if (received.phone) { 
    matchStr.push({ "phone": { "$regex": received.phone, "$options": "i" } }); 
}  

usersTable.aggregate([ 
{ 
    $match: { matchStr } 
}, etc... 

他们没有工作。

确实没有聪明的方法来做到这一点?

回答

1

你不应该使用内$match数组,正确的方法是使用一个对象,并给它分配:

var matchStr = {}; 
if (received.user) { 
    matchStr["_id"] = { "$regex": received.user, "$options": "i" }; 
} 
//etc... 

usersTable.aggregate([ 
{ 
    $match: matchStr 
}, 
//etc... 
+0

感谢尼克 - 那么这是否意味着我仍然可以使用'$比赛:{和matchstr ''? - 我要马上试试 – torbenrudgaard

+1

我已经更新了我的答案,您需要直接传递,'$ match:matchStr' –

+1

完美!非常感谢尼克! - 我不得不停止将mongodb聚合作为字符串(我的背景是MsSql和Oracle hehe)。 Mongo聚合体是物体!现在一切正常。 – torbenrudgaard