corry corry - 1 year ago 85
Node.js Question

NodeJS MongoDB Pass parameter in the aggregation pipeline

How to pass an parameter to the aggregation?
I'm getting the params and trying to pass it using

$match
operator but query returns empty array:

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);
}
});
})


Should I care about order of the operators in pipeline?

Answer Source

Try the following code:-

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);
        } 
    });
})