【问题标题】:Mongoose aggregate method does not work猫鼬聚合方法不起作用
【发布时间】:2016-05-04 06:05:18
【问题描述】:

我有以下几行:

            Score.find({gameId : gameId}).exec(function(err,obj){
                console.log("find length : " + obj.length);
            });

            Score.aggregate([
                {$match: {gameId: gameId}}
            ], function (err, result) {
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

这些行的输出是

result is : []
is there any error : null
find length : 1

我不明白,为什么聚合的“匹配”方法不能按预期工作 - 查找所有匹配属性的文档。我添加了具有相同“正文”的Score.find,以查明该文档是否确实存在并且确实存在。

PS : {gameId: gameId} - 第一个 gameId 是属性名称,第二个是我要查找的 ID 字符串值。


PS2:流利的 api 具有相同的结果:

            Score.aggregate().match({gameId: gameId}).exec(function (err, result){
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

【问题讨论】:

  • 你是否也尝试过流畅的API方法Score.aggregate().match({gameId: gameId}).exec(callback)
  • @chridam - 现在尝试,结果相同
  • 你试过把它转换成猫鼬id吗? mongoose.Types.ObjectId(gameId)new ObjectId(gameId) 原生
  • @styopdev - 这是工作mongoose.Types.ObjectId(gameId),谢谢!请写出来作为答案,我可以接受它

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

你应该将 gameId 字符串转换为 mongodb ObjectId

在猫鼬中

mongoose.Types.ObjectId(gameId)

mongodb原生方式

new ObjectId(gameId)

【讨论】:

    【解决方案2】:

    请尝试以下代码:

    Collection.aggregate([
    {
      $match: {
        cid: ObjectId(req.params.cid),
        createdAt: {
          $gte: new Date(req.query.startDate),
          $lt: new Date(req.query.endDate)
        }
      }
    },
    {
      $group: {
        _id: {
          day: {$dayOfMonth: "$createdAt"},
          month: {$month: "$createdAt"},
          year: {$year: "$createdAt"}
        },
        count: {$sum: 1}
      }
    }
    ]).then(function (result) {
      return res.json(result);
    }, function (error) {
      return res.status(500).send(error);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-24
      • 2015-05-09
      • 2016-12-27
      • 2018-04-10
      • 2015-05-19
      • 2019-12-02
      • 2015-07-27
      • 2023-03-03
      相关资源
      最近更新 更多