猫鼬汇总查询

时间:2020-02-12 18:31:23

标签: node.js mongodb mongoose aggregate

这是问我编写一个简单的聚合查询以显示数据的问题,我有点困惑。您能帮我看看这段代码吗?

如何从以下位置查询数据:

{
        "_id": "5af50e729ba1ae0056dbb436",
        "__v": 0,
        "asset_id": "CHMHCj-sqJdbPwDs_6Y4_Q",
        "asset_type": "youtube_channel",
        "created_at": "2018-05-11T03:30:58.487Z",
        "schema_version": 1,
        "stat": "posts_30d",
        "updated_at": "2018-05-11T03:30:58.487Z",
        "value": "0"
    },

收件人:

[
  {
    _id: '<channel_id>',
    subscribers: [
      {value: Number, date: Date},
      // most recent 10 records
    ],
    posts_30d: [
      {value: Number, date: Date},
      // most recent 10 records
    ]
  },
]

表示channel_id是asset_id,而posts_30d是统计值。 stat值将为“ stat”:“ posts_30d”或“ stat”:“ subscribers”。新数据将根据asset_id和统计值显示。

我尝试使用unwind和project,但是看起来不一样。另外,我使用“限制”来限制帖子的数量,但是结果显示应该每个有10个,但总共显示10个。

db.Stats.aggregate([
    { $unwind: "$stat" },
    { $sort: { updated_at: -1 } },
    { $limit : 5 },
    {
      $project: {
        asset_id: 1,
        value: 1,
        updated_at: 1,
        stat: 1
      }
    },
    {
      $group: {
        _id: "$asset_id",
        sub: {
          $push: {
            value: "$value",
            date: "$updated_at"
          }
        }
      }
    }
  ]).exec(function(err, found) {
    // Log any errors if the server encounters one
    if (err) {
      console.log(err);
    }
    // Otherwise, send the result of this query to the browser
    else {
      res.json(found);
    }
  });

0 个答案:

没有答案