Amira Bedhiafi
Amira Bedhiafi

Reputation: 1

Count with <key,value>

I have created these two functions:

var mapFunction = function () {
if (this.type == "Book")
emit(this.title, this);
};
var reduceFunction = function (key, values) {
return {articles : values};
};

For each key <publisher,year>, I want to retrieve the number of publications.

How can I achieve this ?

This is my current input :

 {"_id": "phd/Klink2006","type": "Phd", "title": "IQForCE - Intelligent Query (Re-)Formulation with Concept-based Expansion", "year": 2006, "publisher": "Verlag Dr. Hut, M?nchen", "authors": ["Stefan Klink"], "isbn": ["3-89963-303-2"]},

Expected output :

Publisher               Year Number of publications
Verlag Dr. Hut, M?nchen 2006 //count of publications in 2006

Upvotes: 1

Views: 54

Answers (1)

Demo - https://mongoplayground.net/p/7aDMu5QhDvk

Use $group and $sum

db.collection.aggregate([
  {
    $group: {
      _id: { year: "$year", publisher: "$publisher" },
      count: { $sum: 1 }
    }
  }
])

You can reshape the data using $project

Demo - https://mongoplayground.net/p/KfZd0CVigw3

  {
    $project: {
      _id: 0, year: "$_id.year", publisher: "$_id.publisher", count: "$count"
    }
  }

Upvotes: 1

Related Questions