【问题标题】:将 JavaScript 转换为 mongoDB 聚合
【发布时间】:2022-01-22 03:57:40
【问题描述】:

我正在搜索如何在 MongoDB 聚合中转换此代码。假设我有这项服务,它将计算即将开始比赛的每项运动中的比赛“夹具”的数量 我有两个模型 Fixture 表示游戏和 Sport 将成为运动,每个 Fixture 都有我们可以在聚合期间分组的运动 ID。 这是一个工作示例

export const countFixtures = async () => {
  const sports = await Sports.find();

  const countFixturesBySport = [];

  for (let index = 0; index < sports.length; index++) {
    const sport = sports[index];
    const countFixtures = await Fixture.countDocuments({
      Sport: sport._id,
      StartDate: { $gt: new Date() },
    });

    countFixturesBySport.push({
      sport: sport.Name,
      sportId: sport._id,
      fixturesCount: countFixtures,
    });
  }

  return countFixturesBySport;
};

我从 mongoDB 中的这段代码开始:

  await Sports.aggregate([
    {
      $lookup: {
        from: 'fixture',
        let: { fixture: '$fixture' },
        pipeline: [
          {
            $match: { $expr: { $eq: ['$_id', '$$fixture'] } },
          },{
            $project:
      {$addFields: {

sport:'Name',
sportId:'_id',
countFixture:''
}}

  ])

【问题讨论】:

标签: node.js mongodb aggregate-functions


【解决方案1】:

Here 你去吧,你在使用$lookup 时走在正确的轨道上,只是需要对实际逻辑进行一些小的调整。

db.sports.aggregate([
  {
    $lookup: {
      from: "fixture",
      let: {
        sportId: "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$Sport",
                "$$sportId"
              ]
            }
          }
        },
        {
          $project: {
            _id: 1
          }
        }
      ],
      as: "matchedFixtures"
    }
  },
  {
    $project: {
      _id: 0,
      sport: "$Name",
      sportId: "$_id",
      fixturesCount: {
        $size: "$matchedFixtures"
      }
    }
  }
])

【讨论】:

  • 非常感谢,感谢您向我解释错误@Tom Slabbaert
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 2015-10-09
  • 2019-08-09
  • 2019-03-15
  • 2014-07-31
  • 2019-02-22
  • 2020-08-20
  • 2020-02-20
相关资源
最近更新 更多