2017-07-17 9 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... 

なしに動作しません。

本当にこれを行うにはスマートな方法はありますか?

あなたは正しい方法は、オブジェクトを使用して、それに割り当てることで、 $match内の配列を使用すべきではありません

答えて

1

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です)。モンゴの集合体はオブジェクトです!すべてが今働きます。 – torbenrudgaard

関連する問題