【问题标题】:How to group embedded objects within an array in mongodb如何在 mongodb 的数组中对嵌入的对象进行分组
【发布时间】:2018-11-29 00:09:38
【问题描述】:

我的文档结构如下:

Item:[{
  product:"shovel"
  price: 100
  dateAdded: 2018-11-28 18:28:12.356
 }
 {
  product:"wheel barrow"
  price: 500
  dateAdded: 2018-11-28 18:28:12.357
 }
 {
  product:"Boot"
  price: 500
  dateAdded: 2018-11-29 18:29:12.357
 }
]

我想根据添加日期对数组中的对象进行分组,即生成表单:

Item:[
 [
  {

  product:"Shovel"
  price: 100
  dateAdded: 2018-11-28 18:28:12.356
 }
 {
  product:"Wheel barrow"
  price: 500
  dateAdded: 2018-11-28 18:28:12.357
 }
 ]
 [
  {
   product:"Boot"
   price: 500
   dateAdded: 2018-11-29 18:29:12.357
 }
 ]
]

关于使用 mongodb 进行聚合查询的任何想法

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以在$dayOfYear 上分组并使用$dateFromString 从您的string 获取日期,如下所示:

    db.collection.aggregate([
      {
        "$group": {
          "_id": {
            $dayOfYear: {
              $dateFromString: {
                dateString: "$dateAdded"
              }
            }
          },
          "data": {
            "$push": "$$CURRENT"
          }
        }
      },
      {
        $project: {
          _id: 0
        }
      }
    ])
    

    结果会是这样的:

    [
      {
        "data": [
          {
            "_id": ObjectId("5a934e000102030405000002"),
            "dateAdded": "2018-11-29 18:29:12.357",
            "price": 500,
            "product": "Boot"
          }
        ]
      },
      {
        "data": [
          {
            "_id": ObjectId("5a934e000102030405000000"),
            "dateAdded": "2018-11-28 18:28:12.356",
            "price": 100,
            "product": "shovel"
          },
          {
            "_id": ObjectId("5a934e000102030405000001"),
            "dateAdded": "2018-11-28 18:28:12.357",
            "price": 500,
            "product": "wheel barrow"
          }
        ]
      }
    ]
    

    然后你可以用 JS 和 Array.reduce 等简单地展平。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2020-06-07
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      相关资源
      最近更新 更多