Average of value fields of documents with id higher than 10

110 Views Asked by At

I'm using express, nodejs, monk.

collection consists of objects: {_id, valueField}

Let's assume that _id is overridden on insert and the id's of 5 documents in the collection range from 1 to 5. They are all integers.

This is what I'm trying now - but I believe the syntax is incorrect. The function returns error 500 and never even gets to the console.log(e).

I want to find all objects in the collection with the _id greater than 10.

collection.aggregate([
                { $match: {
                    "_id":{$gt: 3}
                }},
                { $group: {
                    _id: null,
                    flow: { $avg: "$value"  }
                }}
            ], function (e, docs) {
                if (e) {
                    console.log(e);
                    return;
                }
                console.log(docs);
                res.json(docs);
            });

A function I wrote earlier to get all elements with id higher than 10 works ok:

collection.find({"_id":{$gt: 3}}, {}, function(e,docs){
            res.json(docs);
        });

collection content:

{
  "_id": 1,
  "value": 10
}

{
  "_id": 2,
  "value": 5
}
{
  "_id": 3,
  "value": 4
}

{
  "_id": 4,
  "value": 12
}
{
  "_id": 5,
  "value": 10
}

Expected result:

{
 "_id": null,
 "value": 11
}
1

There are 1 best solutions below

0
On BEST ANSWER

Arrgh!! Should have seen this much sooner. Sorry.

You nee the .col accessor for .aggregate():

var db = require('monk')('localhost/test');
var junk = db.get('junk');


junk.col.aggregate(
  [
    { "$match": { "_id": { "$gt": 3 } } },
    { "$group": {
      "_id": null,
      "flow": { "$avg": "$value" }
    }}
  ],
  function(err,docs) {
    if (err) throw err;
    console.log( JSON.stringify( docs, undefined, 2 ) );
  }
);

Because .aggregate() is not natively supported as a function under the native "Monk" API, so the "deep dive" to the underlying "Node Native" collection is needed.

All apologies.