【问题标题】:NodeJS MongoDB Pass parameter in the aggregation pipeline聚合管道中的NodeJS MongoDB Pass参数
【发布时间】:2016-09-13 09:08:24
【问题描述】:

如何将参数传递给聚合? 我正在获取参数并尝试使用 $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);
            } 
        });
    })

我应该关心管道中操作员的顺序吗?

【问题讨论】:

  • 试试{$match: {name: name}}name 变量在范围内,所以我们只需使用 javascript 在查询中引用它。

标签: node.js mongodb express aggregation-framework mean-stack


【解决方案1】:

试试下面的代码:-

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

【讨论】:

    【解决方案2】:

    您似乎从不使用名为 name 的变量。

    试试这个,把{$match: {name: '$name'}改成{$match: {name: name}

    【讨论】:

      【解决方案3】:

      试试, {$match: {'name': req.params.name}} 这对我有用

      【讨论】:

        【解决方案4】:

        Mongoose 不会投射管道阶段。除非 _id 是数据库中的字符串,否则以下内容将不起作用

        new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
        // Do this instead to cast to an ObjectId
        new Aggregate([{ $match: { _id: 
        mongoose.Types.ObjectId('00000000000000000000000a') } }]);
        

        API 网址:https://mongoosejs.com/docs/api.html#aggregate_Aggregate

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-10
          • 1970-01-01
          • 1970-01-01
          • 2014-12-11
          • 2015-04-24
          • 2020-09-20
          • 2021-04-05
          相关资源
          最近更新 更多