[英]mongodb union 2 collections and count
I have a question about mongodb and node.js. 我对mongodb和node.js有疑问。 I have this collection named PIZZA 我有一个名为PIZZA的收藏
{ title: "bacon" }
{ title: "pepperoni" }
and another collection named ORDERS 和另一个名为ORDERS的集合
{ orderid: 1, pizza: "bacon" }
{ orderid: 2, pizza: "pepperoni" }
{ orderid: 3, pizza: "bacon" }
{ orderid: 4, pizza: "bacon" }
I need to have a result like this 我需要这样的结果
{ title: "bacon", orders: 3 }
{ title: "pepperoni", orders: 1 }
Can I have this with one query? 我可以用一个查询吗?
I need to know how many items there are in collection ORDERS and merge results with collection PIZZA, I'm using MongoClient 我需要知道集合ORDERS中有多少个项目,并将结果与集合PIZZA合并,我正在使用MongoClient
A simple aggregate pipeline should give you the results: 一个简单的聚合管道应该为您提供结果:
db.orders.aggregate([
{
"$group": {
"_id": "$pizza",
"orders": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"title": "$_id",
"orders": 1
}
}
])
Above answer given by @chridam looks good, you just need to use "$project"
rather than "project"
. 上面@chridam给出的答案看起来不错,您只需要使用"$project"
而不是"project"
。 However you may like to use $lookup
但是,您可能想使用$lookup
db.pizza.aggregate([
{
$lookup: {
from: "orders",
localField: "title",
foreignField: "pizza",
as: "totalOrders"
}
},
{
$project: {
_id: 0,
title: 1,
orders: {
$size: "$totalOrders"
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.