我正在使用nodejs从mongodb集合中获取数据。
我从集合中获取了所有数据,但我希望得到 Expected Result (预期结果)中的结果。
我得到了与数据中类似的结果。我必须获得下面提到的过滤器的结果。请帮助我做到这一点
db.collection('collection_name').find({}).toArray(function(err, items)
{
if(err){
console.log(err)
return res.send(500,'something went wrong')
}
else{
res.send({"ISM": items})
}
})
结果如下:
{"data": [{
"CARD_VENDOR": "123",
"TRANSACTION_AMOUNT": "44938.72",
},
{
"CARD_VENDOR": "012",
"TRANSACTION_AMOUNT": "1000.00",
},
{
"CARD_VENDOR": "234",
"TRANSACTION_AMOUNT": "44938.72",
}]
}
预期重用:
{"data": [{
"CARD_VENDOR": "123",
"TRANSACTION_AMOUNT": "44938.72",
},
{
"CARD_VENDOR": "012",
"TRANSACTION_AMOUNT": "1000.00",
},
{
"CARD_VENDOR": "234",
"TRANSACTION_AMOUNT": "44938.72",
}]
},
"filters":{
"CARD_VENDOR" : ["123","012","234"],
"TRANSACTION_AMOUNT": [44938.72,1000.00]
}
答案 0 :(得分:0)
要获得理想的结果,您需要使用 $facet
管道对集合运行汇总操作,该管道允许您处理
同一组输入文档的单个阶段中的多个聚合管道。每个子管道在输出文档中都有其自己的字段,其结果存储为文档数组。
在这种情况下,您的总管道如下:
const pipeline = [
{ '$facet': {
'data': [
{ '$match': {} }
],
'filters': [
{ '$group': {
'_id': null,
'CARD_VENDOR': { '$push': '$CARD_VENDOR' },
'TRANSACTION_AMOUNT': { '$push': '$TRANSACTION_AMOUNT' }
} },
{ '$project': {
'_id': 0
} }
]
} },
{ '$addFields': {
'filters': { '$arrayElemAt': ['$filters', 0 ] }
} }
]
db.collection('collection_name').aggregate(pipeline, (err, results) => {
if (err){
console.log(err)
return res.send(500, 'something went wrong')
} else {
console.log(results)
res.send({ "ISM": results })
}
})
答案 1 :(得分:-1)
您必须操纵您的数组
data: {
"data": [{
"CARD_VENDOR": "123",
"TRANSACTION_AMOUNT": "44938.72",
},
{
"CARD_VENDOR": "012",
"TRANSACTION_AMOUNT": "1000.00",
},
{
"CARD_VENDOR": "234",
"TRANSACTION_AMOUNT": "44938.72",
}],
"filters":{
"CARD_VENDOR" : ["123","012","234"],
"TRANSACTION_AMOUNT": [44938.72,1000.00]
}
}