如何在MongoDB Compass中根据时间分组?

ivqmmu1c  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(199)

最近我正在使用Mongodb数据库,下面是我需要运行查询的文档的数据模型:

{
      "creation_date": {
        "$date": {
          "$numberLong": "1641981205813"
        }
      },
      "user_id": {
        "$oid": "61dedd8b7a520461dd78016b"
      },
      "products": [
        {
          "_id": {
            "$oid": "61dede397a520461dd7818bd"
          },
          "product_id": {
            "$oid": "615071ae8b66e1e9a3d6ea50"
          },
          "payment": true,
          "support_all_payment": false,
          "term_ids": null
        }
      ],
      "carts_info": [
        {
          "_id": {
            "$oid": "61dede397a520461dd7818be"
          },
          "support_type": null,
          "support_price": 0,
          "product_price": 11000,
          "product_type": "all",
          "final_price": 11000,
          "product_id": {
            "$oid": "615071ae8b66e1e9a3d6ea50"
          }
        }
      ],
      "_des": "initial_payment",
      "_type": "online",
      "_token": "9e0cb4d111f642f1a6f482bb04f1f57b",
      "_price": 11000,
      "_status": "unpaid",
      "_terminal_id": "12605682",
      "__v": 0,
      "additional_information": {
        "saman_bank": {
          "MID": "0",
          "ResNum": "61dede387a520461dd7818bb",
          "State": "CanceledByUser",
          "TraceNo": "",
          "Wage": "",
          "Rrn": "",
          "SecurePan": "",
          "HashedCardNumber": "",
          "Status": "1"
        }
      }
    }

这个集合是用户订单,我需要统计今天的订单,所以我需要一个Mongodb Compass的等价查询,与下面的SQL相同:

SELECT count(1) num,
           date(creation_date) date
    FROM orders
    WHERE date(creation_date) = "2023-02-16"
    GROUP BY date

你知道如何在Mongodb Compass上运行这个逻辑吗?

ngynwnxp

ngynwnxp1#

使用$dateTrunc执行仅日期操作。

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $eq: [
          {
            $dateTrunc: {
              date: "$creation_date",
              unit: "day"
            }
          },
          ISODate("2022-01-12")
        ]
      }
    }
  },
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: "$creation_date",
          unit: "day"
        }
      },
      num: {
        $sum: 1
      }
    }
  }
])

Mongo Playground
对于OP的MongoDBv3.6,我们可以使用$dateToString对只有日期的字符串执行字符串比较。

db.collection.aggregate([
  {
    $addFields: {
      dateOnly: {
        "$dateToString": {
          "date": "$creation_date",
          "format": "%Y-%m-%d"
        }
      }
    }
  },
  {
    $match: {
      dateOnly: "2022-01-12"
    }
  },
  {
    $group: {
      _id: null,
      num: {
        $sum: 1
      }
    }
  }
])

Mongo Playground

相关问题