Mongodb数组值先减后和

q8l4jmvw  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(75)

我有一个包含“已发货”和“已交付”两种订单状态的集合。我想以小时为单位计算平均值
公式(已交货1 -已发运1)+(已交货2 -已发运2)+(已交货N -已发运N)/N
这是我收藏

{
    trackingHistory: [
      {
        status: 'Shipped',
        time: ISODate("2022-11-22T06:30:49.000Z")
      },
      {
        status: 'Delivered',
        time: ISODate("2022-11-25T15:30:00.000Z")
      }
    ]
  },
  {
    trackingHistory: [
      {
        status: 'Shipped',
        time: ISODate("2022-11-22T09:29:45.000Z")
      },
      {
        status: 'Delivered',
        time: ISODate("2022-11-23T19:26:00.000Z")
      }
    ]
  }

这是我代码

db.client_order_news.aggregate([
  { $match : { 
      receiverCity : 'New York',
      created_at:{$gte:ISODate("2022-11-01T00:00:00.398Z"),$lt:ISODate("2022-11-30T23:59:59.398Z")},
      "trackingHistory. status":"Shipped",
      "trackingHistory.status":"Delivered"
        } },
        { $project : { _id : 0, trackingHistory : {$filter: {
            input: '$trackingHistory',
            as: 'tracking',
            cond: {$or: [{ $eq: ['$$tracking.status', "Shipped"] }, { $eq: ['$$tracking.status',"Delivered"] }]}
        }}, } },
       {$project: { "$sum": ["$price", { "$subtract": ["$deposits.amount"] } ] }}
]).pretty()
gab6jxml

gab6jxml1#

如果我们可以假设Delivered总是具有比Shipped新的时间戳,则一个选项是使用具有$group步骤的简单$dateDiff

db.collection.aggregate([
  {$project: {trackingHistory: "$trackingHistory.time", _id: 0}},
  {$group: {
      _id: 0,
      timeDiff: {
        $push: {
          $abs: {
            $dateDiff: {
              startDate: {$first: "$trackingHistory"},
              endDate: {$last: "$trackingHistory"},
              unit: "hour"
            }
          }
        }
      }
    }
  },
  {$project: {averageHour: {$avg: "$timeDiff"}, _id: 0}}
])

了解它在playground example上的工作原理

相关问题