0

Say I have a collection with documents like the following:

{
   title: "First",
   sub_items: ['test', 'another test', 'whatever]
},
{
   title: "Second",
   sub_items: ['something', 'something else']
}

And I would like to get output like below:

{"First", 3},
{"Second, 2}

What is the best way to do this? I have implemented it using the map function like below:

db.coll.find().map(
   function(item)
   {
      return {title: item.title, count: item.sub_items.length};
   }
);

When attempting to get the above results, would I be better off from a performance perspective to try and use something like aggregate or mapReduce?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

1 Answers1

2

If you are using MongoDB 2.6 or later, you can use the $size aggregation operator to get results close to what you want. From the documentation for $size:

Counts and returns the total the number of items in an array.

Below is an untested example:

db.coll.aggregate([
    {"$project" : {"title" : 1, "count" : {"$size":"$sub_items"}}}
])
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
  • Nice, that definitely looks simpler. Do you know how it would compare performance wise? – Abe Miessler Oct 09 '14 at 15:20
  • Using the aggregation framework is most certainly multiple times faster than map-reduce. The accepted answer for [`this question`](http://stackoverflow.com/questions/13908438/is-mongodb-aggregation-framework-faster-than-map-reduce) should give you an idea. – Anand Jayabalan Oct 09 '14 at 16:23