MongoDB查询以一个json格式发送所有字段的响应



我必须以一个JSON格式发送响应,其中有三个品牌名称以及三个制造商名称。我在最后粘贴了一个示例。

我的代码-

getFilterData: function (req, res, next) {
console.log('Itemfilterlist getAll ');
let filterlist = []
let agg = [  {'$match': {'generic_name': req.body.generic_name, 'form_name': req.body.form_name, 'dose_size': req.body.dose_size}}, 
{'$sort': {'mrp': 1}}, 
{'$limit': 3},
{'$group': {_id:'$id',  "generic_name": {$first:"$generic_name"},
"form_name": {$first:"$form_name"},
"dose_size": {$first:"$dose_size"},
"subcategory_name": {$first:"$subcategory_name"},
brand1: {$push: { "brand_name": "$brand_name", "manufacturer_name": "$manufacturer_name"}}}}
]
let i = 0;
MasterModel.aggregate(agg,  function (err, arrList) {
if (err) {
next(err);
}
else {   
for (let h of arrList) {
h.id = ++i            
filterlist.push(h);
}                                                                       
res.json({ filterList: filterlist })

}
});
},

我使用带有push accumulator的组聚合来显示数据,在组查询的帮助下,但我得到了这个JSON数据响应:-

"filterList": [
{
"_id": null,
"generic_name": "Ademetionine",
"form_name": "Tablets-MD",
"dose_size": "400MG",
"subcategory_name": "Others",
"brand1": [
{
"brand_name": "CARTISURE 400 MG TAB",
"manufacturer_name": "Zoic Lifesciences"
},
{
"brand_name": "ADENORICH 400 MG TAB",
"manufacturer_name": "Future Pharma Pvt Ltd"
},
{
"brand_name": "ENSAME 400 TAB",
"manufacturer_name": "ICARUS HEALTHCARE"
}
],
"id": 1
}
]

但我希望我的JSON格式是这样的:-

{
id: 1,
molecule: 'Heparin',
form: 'Ointments',
strength: '50IU',
sub_category: 'CARDIO VASCULAR SYSTEM',
brand_name_1: 'HEPTRAL(Abbott)',
brand_name_2: 'HYSAM(Alkem)',
brand_name_3: 'THROMBOMARK(Mankind)',
}

您可以在聚合管道中添加$projection步骤。比如:

db.collection.aggregate([
{
$project: {
brand_name_1: {
$concat: [
{$arrayElemAt: ["$brand1.brand_name", 0]}, "(",
{$arrayElemAt: ["$brand1.manufacturer_name", 0]}, ")"
]
},
brand_name_2: {
$concat: [
{$arrayElemAt: ["$brand1.brand_name", 1]}, "(",
{$arrayElemAt: ["$brand1.manufacturer_name", 1]}, ")"
]
},
brand_name_3: {
$concat: [
{$arrayElemAt: ["$brand1.brand_name", 2]}, "(",
{$arrayElemAt: ["$brand1.manufacturer_name", 2]}, ")"
]
},
sub_category: "$subcategory_name",
strength: "$dose_size",
form: "$form_name",
molecule: "$generic_name",
id: 1,
_id: 0
}
}
])

看看它在操场的例子中是如何工作的

相关内容

  • 没有找到相关文章

最新更新