Mauro Sala Mauro Sala - 2 months ago 23
Javascript Question

mongodb union 2 collections and count

I have a question about mongodb and node.js. I have this collection named PIZZA

{ title: "bacon" }
{ title: "pepperoni" }


and another collection named 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

Answer

Above answer given by @chridam looks good, you just need to use "$project" rather than "project". However you may like to use $lookup

db.pizza.aggregate([
{
    $lookup: { 
      from: "orders",
      localField: "title",
      foreignField: "pizza",
      as: "totalOrders"
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      orders: { 
        $size: "$totalOrders" 
      }
    }
  }
])