Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB聚合管道:使用$cond返回$match阶段?_Mongodb - Fatal编程技术网

MongoDB聚合管道:使用$cond返回$match阶段?

MongoDB聚合管道:使用$cond返回$match阶段?,mongodb,Mongodb,我正在尝试构建查询,使其具有与数据库交互的真正有趣的方式。其中之一是搜索特定年份范围内的文档。我的thinkingnwas需要构建一个聚合管道,在该管道中检查搜索表单中是否选择了年份范围,然后返回匹配的文档。如果未选择任何范围,则返回所有文档并转到聚合管道的下一阶段 以下是我尝试过的(在聚合中只有一个阶段,因为我还没有设法使第一个阶段起作用): db.collection('archives').aggregate([ {$cond:{if:yearStart.length==4&&yearE

我正在尝试构建查询,使其具有与数据库交互的真正有趣的方式。其中之一是搜索特定年份范围内的文档。我的thinkingnwas需要构建一个聚合管道,在该管道中检查搜索表单中是否选择了年份范围,然后返回匹配的文档。如果未选择任何范围,则返回所有文档并转到聚合管道的下一阶段

以下是我尝试过的(在
聚合中只有一个阶段,因为我还没有设法使第一个阶段起作用):

db.collection('archives').aggregate([
{$cond:{if:yearStart.length==4&&yearEnd==4},
然后:{$match:
{$和:
[
{年份:{$gte:yearStart},
{年份:{$lte:yearEnd}
]
}
},
else:{$match:{}
}
]).toArray((错误,文档)=>{
如果(错误)抛出(错误)
res.json(文档)

})
首先使用本机JavaScript条件在管道外部创建要与一起使用的查询对象,因为使用运算符仅适用于指定的管道阶段。这是你用的 这是一个管道步骤,因此引发了错误

考虑以下几点:

const query = { "year": { } };
if (yearStart.length === 4 && yearEnd === 4) {
    query["year"]["$gte"] = yearStart;
    query["year"]["$lte"] = yearEnd;    
}

db.collection('archives').aggregate([ { "$match": query } ]).toArray((err, docs) => {
    if (err) throw (err);
    res.json(docs);
});
或者使用方法作为

db.collection('archives').find(query).toArray((err, docs) => {
    if (err) throw (err);
    res.json(docs);
});

首先使用本机JavaScript条件创建要与管道外的一起使用的查询对象,因为使用运算符仅适用于指定的管道阶段。这是你用的 这是一个管道步骤,因此引发了错误

考虑以下几点:

const query = { "year": { } };
if (yearStart.length === 4 && yearEnd === 4) {
    query["year"]["$gte"] = yearStart;
    query["year"]["$lte"] = yearEnd;    
}

db.collection('archives').aggregate([ { "$match": query } ]).toArray((err, docs) => {
    if (err) throw (err);
    res.json(docs);
});
或者使用方法作为

db.collection('archives').find(query).toArray((err, docs) => {
    if (err) throw (err);
    res.json(docs);
});

聚合管道是一个管道。无条件的。保存应用层的“如果在搜索表单中选择了年份范围”逻辑,并根据用户输入执行不同的查询。聚合管道是一个管道。无条件的。保存应用层的“如果在搜索表单中选择了年份范围”逻辑,并根据用户输入执行不同的查询。