如何按ID仅将没有parentId的项目和具有parentId的项目保留第一项的项目分组?

时间:2018-10-22 04:52:14

标签: javascript mongodb aggregate

我有一个像下面这样的集合,并且有该集合,我想用一个ID将该项目分组,该ID没有该项。能帮我吗?

let item=[
             {id:'001', name:'A', qty:10,},
             {id:'002', name:'B', qty:5, parentId:'001'},
             {id:'003', name:'C', qty:8, parentId:'001'},
             {id:'001', name:'A', qty:-5,},
             {id:'002', name:'B', qty:-5, parentId:'001'},
             {id:'003', name:'C', qty:-8, parentId:'001'}
             ]

我只希望将没有parentId的项目分组,这是我的结果。

let item=[
             {id:'001', name:'A', qty:5,},                 
             {id:'002', name:'B', qty:5, parentId:'001'},
             {id:'003', name:'C', qty:8, parentId:'001'}
         ]

2 个答案:

答案 0 :(得分:0)

let item = [{
    id: '001',
    name: 'A',
    qty: 10,
  },
  {
    id: '002',
    name: 'B',
    qty: 5,
    parentId: '001'
  },
  {
    id: '003',
    name: 'C',
    qty: 8,
    parentId: '001'
  },
  {
    id: '001',
    name: 'A',
    qty: -5,
  },
  {
    id: '002',
    name: 'B',
    qty: -5,
    parentId: '001'
  },
  {
    id: '003',
    name: 'C',
    qty: -8,
    parentId: '001'
  }
]

item = item.reduce((a, c) => {
  const ex = a.find((v) => v.id === c.id)
  if (ex) {
    if (!ex.parentId) {
      ex.qty += c.qty;
    }
  } else {
    a.push(c);
  }
  return a;
}, [])

console.log(item);

答案 1 :(得分:0)

您可以使用

db.collectionName.aggregate([
    {
        $group: {
            "_id": {
                "id": "$id",
                "parentId": "$parentId"
            },
            qtyArray: {
                $push: {
                    "qty": "$qty",
                }
            }
        }
    },
    {
        $project: {
            count: {
                $cond: [
                    {
                        $not: ["$_id.parentId"]
                    }, 
                    {
                        "qtyTotal": { $sum: "$qtyArray.qty" }
                    },
                    {
                        $arrayElemAt: [ "$qtyArray", 0 ]
                    }
                ]
            }

        }
    }
])