如何在mongodb中对数组内的嵌入式对象进行分组

时间:2018-11-29 00:09:39

标签: mongodb aggregation-framework

我的文档结构如下:

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进行聚合查询的任何想法

1 个答案:

答案 0 :(得分:0)

您可以像这样在$dayOfYear上分组并使用$dateFromStringstring获取日期:

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等进行平整操作。