3

My document is of format:

{
  "PItems": {
    "Workspaces": [
      {
        "Key": "Item1",
        "Size": 228.399,
        "Foo": "bar"
      },
      {
        "Key": "Item2",
        "Size": 111.399,
        "Bar": "baz"
      },
      {
        "Key": "Item2",
        "Size": 636.66,
        "Baz": "foo"
      }

    ]
  }
}

I need to find the average size of each items from all the documents in the collection. How do I do that?

Expected output:

Item1: 346.12

Item2: 563.58

I have tried the following:

db.Resources.mapReduce(
  function() { 
    this.PItems.Workspaces.forEach(
       function(z) {
          emit(z.Key, z.Size);
       }
    );
  },
  function(item, space) {
    var total = 0;
    for ( var i=0; i<space.length; i++ )
        total += size[i];
    return { avg : total/space.length };
  },
  out: { inline: 1 }
);

I am getting a syntax error: SyntaxError: missing ) after argument list. What am I missing here?

Nemo
  • 24,540
  • 12
  • 45
  • 61
  • Why mapreduce not aggregation? As aggregation is much faster then the mapreduce – Ashh Jan 03 '19 at 09:53
  • Edited the example. In my case item can repeat in a document. How can I do it using aggregation? – Nemo Jan 03 '19 at 09:56
  • Could you post the expected output as well – Ashh Jan 03 '19 at 09:58
  • Edited with expected output – Nemo Jan 03 '19 at 10:03
  • Your expected output is not being produced by your sample collection. Could your explain how `Item1: 346.12 Item2: 563.58`? – Ashh Jan 03 '19 at 10:19
  • The average is over multiple documents. Only one document is shown in the above example. I wanted to point out that the key can repeat in a single document which is why I thought map reduce may be the way to go. – Nemo Jan 03 '19 at 10:22
  • 1
    My be you are looking for something like this `db.collection.aggregate([ { $unwind: "$PItems.Workspaces" }, { $group: { _id: "$PItems.Workspaces.Key", average: { $avg: "$PItems.Workspaces.Size" } } } ])` https://mongoplayground.net/p/isr2COOVTjF – Ashh Jan 03 '19 at 10:25
  • Thanks a lot, that did the trick. Was not aware of "$unwind"! – Nemo Jan 03 '19 at 20:47

0 Answers0