动态构建聚合查询的json结构

时间:2017-07-17 14:08:57

标签: javascript arrays mongodb

我想构建一个匹配包含数据的字段的查询。

我试过了:

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 个答案:

答案 0 :(得分:1)

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

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

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