Mongo $projection,??????????????

Posted

技术标签:

【中文标题】Mongo $projection,你能扁平化一个子文档数组吗?【英文标题】:Mongo $projection, can you flat a sub-document array? 【发布时间】:2019-12-10 17:08:03 【问题描述】:

我想知道是否有一种方法可以通过投影嵌套的子文档数组来“展平”,以便我可以使用它来根据类型汇总其条目。

我的文档如下所示:


      "order_id":12345,
      "date":8/17/2019,
      "payment":
        status:1,
        transactions:[
          type: 1, amount:200,
          type: 2, amount:250,
          type: 3, amount:50,
          type: 4, amount:50,
        ]
      
    
    
    I would like to see if you can "flatten" it to something like this using $project:
    
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 1, 
      "amount":200
     ,
     
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 2, 
      "amount":250
     ,
     
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 4, 
      "amount":50
     ,
     
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 4, 
      "amount":50
     
      
    
    
  

我的主要目标是汇总类型 1 和 3 交易的所有金额以及类型 2 和 4 的所有交易。

Any help would be great.

【问题讨论】:

【参考方案1】:

以下查询可以获得预期的输出:

db.check.aggregate([
    
        $unwind:"$payment.transactions"
    ,
    
        $project:
            "_id":0,
            "order_id":1,
            "date":1,
            "status":"$payment.status",
            "type":"$payment.transactions.type",
            "amount":"$payment.transactions.amount"
        
    
]).pretty()    

输出:


    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 1,
    "amount" : 200


    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 2,
    "amount" : 250


    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 3,
    "amount" : 50


    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 4,
    "amount" : 50

【讨论】:

以上是关于Mongo $projection,??????????????的主要内容,如果未能解决你的问题,请参考以下文章

mongo删除重复行

无法在学说 mongo 查询中增加值

mongo的安装

mongo聚合例子

nodejs入门篇---创建project并具体解释

将 mongo 查询转换为 spring-data-mongo 查询