MongoDB的单个查询中的多个组

问题描述 投票:0回答:1

我有一组具有不同“标签”和“目的”的多个记录

{
    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
}

我想首先用“label”id分组我的记录,然后用“目的”分组,并显示如下结果:

[
    {
        "label" : "5c94fb7722ac2a0017e70857",
        "balance" : {
            "purchasing" : 240404,
            "deposit" : 4342
        }
    },
    {
        "label" : "5c94fb7722ac2rewt17e7084w58",
        "balance" : {
            "Purchasing" : 455356,
            "Deposit" : 56577
        }
    },
]
node.js mongodb
1个回答
-1
投票

在过去,我使用了groupBy lodash func。见: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
}]

然后调用Lodash方法groupBy作为_.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/[email protected]/lodash.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.