Reputation: 10730
I'm working on an eCommerce based website using MongoDb
.
In my db collection I have 2 type of documents
Company details Item
{ doc_type : 'company',
name : 'Acer',
type : 'Laptops',
helpline : '1800-200-000'
}
Item Details
{doc_type : "item",
item_id : 1001,
price : 2000,
discount : 20}
Now in product page i need to get data from both document.
so, first i run
db.collection.find({doc_type:'item', item_id : 1001 });
to show product data and then
db.collection.find({doc_type:'company', name: "Acer"});
to get company data.
Is their any way to reduce these 2 calls to one and get data in single result set.
like
{
company : { //company data},
item : { //item details }
}
Upvotes: 2
Views: 5912
Reputation: 812
To achieve the sample output that you have shared, along with the $match
and $group
stages, I have added a $project
stage.
db.col.aggregate([
{
$match:
{
$or: [
{doc_type:'item', item_id : 1001 },
{doc_type:'company', name: 'Acer'}
]
}
},
{
$group:
{
_id: null,
"company_name": {$max: "$name"},
"company_type": {$max: "$type"},
"company_helpline": {$max: "$helpline"},
"item_price": {$max: "$price"},
"item_discount": {$max: "$discount"}
}
},
{
$project:
{
_id: 0,
'company' : {
'name': '$company_name',
'type': '$company_type',
'helpline': '$company_helpline',
},
'item' : {
'price': '$item_price',
'discount': '$item_discount'
}
}
}
]).pretty()
Output :
{
"company" : {
"name" : "Acer",
"type" : "Laptops",
"helpline" : "1800-200-000"
},
"item" : {
"price" : 2000,
"discount" : 20
}
}
Upvotes: 3
Reputation: 9285
You can achieve this using aggregation using a $match
and a $group
stage.
The query would be :
db.it.aggregate([
{$match:
{$or: [
{doc_type:'item', item_id : 1001 },
{doc_type:'company', name: "Acer"}
]
}
},
{$group:
{_id: null,
"compagny_name": {$max: "$name"},
"compagny_type": {$max: "$type"},
"compagny_helpline": {$max: "$helpline"},
"item_price": {$max: "$price"},
"item_discount": {$max: "$discount"}
}
}] )
this output :
{
"_id":null,
"compagny_name":"Acer",
"compagny_type":"Laptops",
"compagny_helpline":"1800-200-000",
"item_price":2000,
"item_discount":20
}
Upvotes: 1