0

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33

2 Answers2

0

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
        }
    }
])
chridam
  • 100,957
  • 23
  • 236
  • 235
0

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" 
      }
    }
  }
])
Arif Khan
  • 5,039
  • 2
  • 16
  • 27