自定义 return MongoDB 聚合

Custom return MongoDB aggregate

我正在尝试使用 MongoDB 进行一些测试,并且我想出了一些更简单的 MySQL 查询 MongoDB。现在,我有这个稍微复杂的查询。

我有这个查询,告诉我在特定时间段内是否有来自确定用户的消息:

SELECT CASE WHEN count(1) = 0 THEN false ELSE true END AS 'value'
FROM messages m
WHERE m.time BETWEEN 0 AND 1652471890 AND m.user_id = '256f5280-fb49-4ad6-b7f5-65c4329d46e0';

目前我正在尝试这样做以计算数量并发出自定义值 0/1:

当前 MongoDB 汇总

    db.messages.aggregate([
        { $match: 
            {
            $and: [
              {user_id: "256f5280-fb49-4ad6-b7f5-65c4329d46e0"},
              {time: {$gt: 1622471890, $lt: 1822471890}}
            ]
            } 
        },
        { $count: "value"}
    ])

数据集:

    [
    {
        "time": 1422471890,
        "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
        "message": "This is an example of my db"
    },
    {
        "time": 1622471890,
        "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
        "message": "This is an example of my db (1)"
    },
    {
        "time": 1622471890,
        "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
        "message": "This is an example of my db (2)"
    },
    {
        "time": 1622471890,
        "user_id": "e194d667-d79f-4262-94b1-ecf4561c9418",
        "message": "This is an example of my db (3)"
    },
    {
        "time": 1922471890,
        "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0"<
        "message": "This is an example of my db (4)"
    }
    ]

Return:

对于这个数据集,它是 returning:

{ "value" : 2 }

我正在尝试 return:

如果计数 > 0: { "value": 1 }

如果计数 <= 0: { "value": 0 }

您只需要一个 $addFields 阶段即可将 $cond 应用到您的 value

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          user_id: "256f5280-fb49-4ad6-b7f5-65c4329d46e0"
        },
        {
          time: {
            $gte: 1622471890,
            $lt: 1822471890
          }
        }
      ]
    }
  },
  {
    "$count": "value"
  },
  {
    "$addFields": {
      "value": {
        "$cond": {
          "if": {
            "$gt": [
              "$value",
              0
            ]
          },
          "then": "$value",
          "else": 0
        }
      }
    }
  },
  {
    "$unionWith": {
      "coll": "collection",
      "pipeline": [
        {
          $limit: 1
        }
      ]
    }
  },
  {
    "$sort": {
      value: -1
    }
  },
  {
    $limit: 1
  },
  {
    "$project": {
      _id: 0,
      value: {
        "$ifNull": [
          "$value",
          0
        ]
      }
    }
  }
])

这里是Mongo Playground供您参考。