【问题标题】:MongoDB aggregation grouping documents without accumaltionMongoDB聚合分组文档不累积
【发布时间】:2016-05-12 06:40:38
【问题描述】:

使用 MongoDB 的聚合管道,我希望能够按值对文档进行分组,而无需任何累积。

例如,我想按key对这个集合进行分组:

[
   {
      "_id":"323232",
      "name":"Something",
      "key":"A",
      "price":"100"
   },
   {
      "_id":"157236",
      "name":"Another thing",
      "key":"B",
      "price":75
   },
   {
      "_id":"555232",
      "name":"Something or another",
      "key":"B",
      "price":78
   }
]

想要的结果:

[
   {
       "_id":"A",
       "results": [
           {
              "_id":"323232",
              "name":"Something",
              "key":"A",
              "price":"100"
           }
       ]
   },
   {
       "_id":"A",
       "results": [
           {
              "_id":"157236",
              "name":"Another thing",
              "key":"B",
              "price":75
           },
           {
              "_id":"555232",
              "name":"Something or another",
              "key":"B",
              "price":78
           }
       ]
   }
]

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    这个怎么样?

    db.test.aggregate([
        {
            $sort : {"price" : 1}
        },
        {
            $group : {
                _id : '$key',
                results : {
                    $push : {
                        "_id":"$_id",
                        "name":"$name",
                        "key":"$key",
                        "price":"$price"
                    }
                }
            }
        }
    ]).pretty()
    

    【讨论】:

    • 谢谢。然后我将如何通过price 订购results 中的文档?
    • 您可以尝试先使用$sort按价格对所有文档进行排序,然后使用$group。查看编辑。
    【解决方案2】:

    检查一下

    db.coll.aggregate([
                        { "$group" : {
                                  '_id' :'$key',
                                  result: {$push:'$$ROOT'}
                                }
                        }
                     ]);
    

    【讨论】:

    • 谢谢。然后我将如何通过price 订购results 中的文档?
    猜你喜欢
    • 2019-03-25
    • 2017-09-19
    • 2016-07-28
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多