Javascript 动态构建聚合查询的json结构
我想构建一个与包含数据的字段相匹配的查询 我试过这个:Javascript 动态构建聚合查询的json结构,javascript,arrays,mongodb,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 (r
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中使用数组,正确的方法是使用对象并分配给它:
var matchStr = {};
if (received.user) {
matchStr["_id"] = { "$regex": received.user, "$options": "i" };
}
//etc...
usersTable.aggregate([
{
$match: matchStr
},
//etc...
谢谢尼克-这是否意味着我仍然可以使用$match:{matchStr}一旦我更新了我的答案,我就要试试,你需要直接通过,$match:matchStrPERFECT!!!非常感谢尼克!!!-我必须停止将mongodb聚合看作字符串我的背景是MsSql和Oracle hehe。Mongo聚合是对象!!现在一切都好了。