MongoDB的单个查询中的多个组

时间:2019-03-28 14:15:10

标签: node.js mongodb

我有一组具有不同“标签”和“用途”的多条记录

{
    billNumber: "",
    _id: "5c94fbc222ac2a0017e70859",
    label: "5c94fb7722ac2a0017e70857",
    purpose: "Purchasing",
    date: "2019-03-27T00:00:00.000Z",
    amount: 200000
},
{
    billNumber: "",
    _id: "5c95e300a634360017498c39",
    label: "5c94fba222ac2a0017e70858",
    purpose: "Deposit",
    date: "2018-05-08T00:00:00.000Z",
    amount: 792
}

我想先用“标签” id将记录分组,然后用“用途”将记录分组,并显示如下结果:

[
    {
        "label" : "5c94fb7722ac2a0017e70857",
        "balance" : {
            "purchasing" : 240404,
            "deposit" : 4342
        }
    },
    {
        "label" : "5c94fb7722ac2rewt17e7084w58",
        "balance" : {
            "Purchasing" : 455356,
            "Deposit" : 56577
        }
    },
]

1 个答案:

答案 0 :(得分:-1)

过去,我为此使用过groupBy lodash函数。参见:https://lodash.com/docs/4.17.11#groupBy

因此以对象数组构建记录的集合:

const records = [{
    billNumber: "",
    _id: "5c94fbc222ac2a0017e70859",
    label: "5c94fb7722ac2a0017e70857",
    purpose: "Purchasing",
    date: "2019-03-27T00:00:00.000Z",
    amount: 200000
},
{
    billNumber: "",
    _id: "5c95e300a634360017498c39",
    label: "5c94fba222ac2a0017e70858",
    purpose: "Deposit",
    date: "2018-05-08T00:00:00.000Z",
    amount: 792
}]

然后以groupBy的形式调用Lodash方法_.groupBy(records, 'label');,该方法将返回:

$: { 5c94fb7722ac2a0017e70857: 
   [ { billNumber: '',
       _id: '5c94fbc222ac2a0017e70859',
       label: '5c94fb7722ac2a0017e70857',
       purpose: 'Purchasing',
       date: '2019-03-27T00:00:00.000Z',
       amount: 200000 } ],
  5c94fba222ac2a0017e70858: 
   [ { billNumber: '',
       _id: '5c95e300a634360017498c39',
       label: '5c94fba222ac2a0017e70858',
       purpose: 'Deposit',
       date: '2018-05-08T00:00:00.000Z',
       amount: 792 } ] }

这是一个有效的代码段:

const records = [{
    billNumber: "",
    _id: "5c94fbc222ac2a0017e70859",
    label: "5c94fb7722ac2a0017e70857",
    purpose: "Purchasing",
    date: "2019-03-27T00:00:00.000Z",
    amount: 200000
},
{
    billNumber: "",
    _id: "5c95e300a634360017498c39",
    label: "5c94fba222ac2a0017e70858",
    purpose: "Deposit",
    date: "2018-05-08T00:00:00.000Z",
    amount: 792
}]

const grouped = _.groupBy(records, 'label');

console.log(grouped)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>