获取具有相同 time_stamp 但不同标识符的记录

Fetching records with same time_stamp but different identifiers

当前数据:

    [
      {
        "_id": "6239bd7a465f8d1fbfc80f95",
        "tag_id": "620e23a6450b9ea1a1e31d75",
        "time_stamp": "2022-02-28T19:55:55.666000",
        "is_deleted": false,
        "value": 20
      },
      {
        "_id": "623ef6e4cd717dc11aee942b",
        "tag_id": "620e23a6450b9ea1a1e31d75",
        "time_stamp": "2022-03-01T20:55:55.666000",
        "is_deleted": false,
        "value": 20
      },
      {
        "_id": "623ef6f0cd717dc11aee94f6",
        "company_id_rdb": 3,
        "tag_id": "620e23a6450b9ea1a1e31d75",
        "time_stamp": "2022-03-02T21:55:55.666000",
        "is_deleted": false,
        "value": 20
      },
      {
        "_id": "623ef718cd717dc11aee97d9",
        "company_id_rdb": 3,
        "tag_id": "620e23a6450b9ea1a1e31da6",
        "time_stamp": "2022-03-02T19:55:55.666000",
        "is_deleted": false,
        "value": 20
      },
      {
        "_id": "623ef722cd717dc11aee9895",
        "tag_id": "620e23a6450b9ea1a1e31da6",
        "time_stamp": "2022-03-03T20:55:55.666000",
        "is_deleted": false,
        "value": 20
      },
      {
        "_id": "623ef72ccd717dc11aee9943",,
        "tag_id": "620e23a6450b9ea1a1e31da6",
        "time_stamp": "2022-03-04T21:55:55.666000",
        "is_deleted": false,
        "value": 20
      }
    ]

最终的对象应该是这样的:

      {
    
        "time_stamp": "2022-03-04T21:55:55.666000",
        "value": 60,
        "tags_count":2
      },
      {
        "time_stamp": "2022-02-28T19:55:55.666000",
        "tags_count":2,
        "value": 60
      },
      {
        "time_stamp": "2022-03-03T20:55:55.666000",
        "tags_count":2,
        "value": 60
      },

我尝试了以下查询但没有成功:

db.getCollection('data').aggregate([
  {$match:{"tag_id":{$in:[ObjectId("620e23a6450b9ea1a1e31da6"),ObjectId("620e23a6450b9ea1a1e31d75")]}}},
  {$group:{"_id":"$time_stamp","value":{$sum:"$value"},"count":{$sum:1}}}
])

我有一个集合,其中的记录对于不同的标签 (tag_id) 各有 10 分钟的差异,并且每个标签都有一个值。我想写一个查询,在其中我传递一个标签列表让我们说 t1 和 t2 和一个时间范围(从 $ 直到),并且查询应该 return 在每个时间戳传递的标签值的总和进入那个范围。

看起来你快到了,也许是这样的:

db.collection.aggregate([
{
 $match: {
  "tag_id": {
    "$in": [
      "620e23a6450b9ea1a1e31da6",
      "620e23a6450b9ea1a1e31d75"
    ]
  },
  "time_stamp": {
    "$gte": "2022-02-28T19:55:55.666000",
    "$lte": "2022-03-03T20:55:55.666000"
  }
 }
},
{
  $group: {
    "_id": "$time_stamp",
    "value": {
      $sum: "$value"
    },
    "count": {
      $sum: 1
    }
   }
  }
])

解释:

  1. 按 tag_id 和 time_stamp 范围匹配
  2. 按 time_stamp 分组并求和值 + count

playground