[英]NodeJs, Mongoose find and populate works but aggregate, match and lookup doesn't
[英]How to pass variables to aggregate(match) with Mongoose and NodeJS?
我有這種文件:
{
"_id" : 1,
"time": {
"start": ISODate("2016-01-18T00:12:41.000Z"),
"end": ISODate("2016-01-18T05:12:41.000Z")
},
"subject":"javascript",
"class": "ABC"
}
...
我有客戶端/服務器應用程序,客戶端將使用四個變量將請求發送到服務器: timeS
, timeE
, sub
, class
。 它們可能是空字符串。
在服務器中,如何編寫聚合查詢以查找與過濾條件匹配的記錄? 我想忽略為空的搜索詞。
var query = db.collection.aggregate([
{"$match": {"$and":[]}}
]);
例:
如果timeS
不為空,我希望$match
與$eq
。
如果timeS
和timeE
都不為空,我希望將$match
與$gte:timeS, $lte:timeE
。
根據輸入變量的存在動態創建匹配條件。
var matchCriteria = {}, pipeline;
var timeS, timeE, sub, clazz; //initialize them from your input
if (timeS) {
matchCriteria['time.start'] = timeS;
}
if (timeE) {
matchCriteria['time.end'] = timeE;
}
if (sub) {
matchCriteria.subject = sub;
}
if (clazz) {
matchCriteria.class = clazz;
}
pipeline = [
{
$match: matchCriteria
}
];
db.collection.aggregate(pipeline);
您可能需要執行其他檢查,例如至少存在一個變量,以確保匹配條件不為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.