NodeJS MongoDB传递参数在聚合pipe道中

如何将parameter passing给聚合? 我得到的参数,并试图传递它使用$match运算符,但查询返回空数组:

 app.get('/api/:name', function(req, res){ var name = req.params.name; console.log(name); db.collection('coll').aggregate([{$match: {name: '$name'}}, {$unwind: { path: "$dates", includeArrayIndex: "idx" } }, { $project: { _id: 0, dates: 1, numbers: { $arrayElemAt: ["$numbers", "$idx"] }, goals: { $arrayElemAt: ["$goals", "$idx"] }, durations: { $arrayElemAt: ["$durations", "$idx"]}}}]).toArray(function(err, docs) { if (err) { assert.equal(null); } else { console.log(docs); res.json(docs); } }); }) 

我应该关心pipe道运营商的订单吗?

试试下面的代码:

 app.get('/api/:name', function(req, res){ var name = req.params.name; var query = [{$match: {'name': name}}, {$unwind: { path: "$dates", includeArrayIndex: "idx" } }, { $project: { _id: 0, dates: 1, numbers: { $arrayElemAt: ["$numbers", "$idx"] }, goals: { $arrayElemAt: ["$goals", "$idx"] }, durations: { $arrayElemAt: ["$durations", "$idx"]}}}]; db.collection('coll').aggregate(query).toArray(function(err, docs) { if (err) { assert.equal(null); } else { console.log(docs); res.json(docs); } }); }) 

看来你永远不会使用名字variables。

试试这个,将{$match: {name: '$name'}更改为{$match: {name: name}