1

Good afternoon everyone.

I have an Array inside a MongoDB Document. I wan't to find a Volume inside it and make an average for whole collection on Volume parameter.

Document inside a MongoDB:

MongoDB screen

As you can see I have array inside array. I will have a lot of the same type documents and I need to make an average calculation between every document on Volumeparameter.

Problematic area of code(This is not working just showcasing my try.

function simplePipeline(db, callback) {
    const collection = db.collection('ADABTC');
    collection.aggregate(
        [
            { '$group': { 'Volume': { '$avg': 'Array.Volume' } } }
        ],
        function(err, cursor) {
            assert.equal(err, null);

            cursor.toArray(function(err, documents) {
                console.log(documents)
                callback(documents);
            });
        }
    );
}

Just in case I can connect to DB username:password just for example.

How I should specify it NodeJS?

NodeJS Full Code

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://username:[email protected]/<dbname>?retryWrites=true&w=majority';

// Database Name
const dbName = 'Crypto';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// Use connect method to connect to the Server
client.connect(function(err, client) {
    assert.equal(null, err);
    console.log("Connected correctly to server");

    const db = client.db(dbName);

    simplePipeline(db, function() {
        client.close();
    });
});

function simplePipeline(db, callback) {
    const collection = db.collection('ADABTC');
    collection.aggregate(
        [
            { '$group': { 'Volume': { '$avg': 'Array.Volume' } } }
        ],
        function(err, cursor) {
            assert.equal(err, null);

            cursor.toArray(function(err, documents) {
                console.log(documents)
                callback(documents);
            });
        }
    );
}

1 Answer 1

1

Your $group syntax is just wrong:

Groups input documents by the specified _id expression and for each distinct grouping, outputs a documen

A $group stage must have a _id field specified. to group the entire collection just put any constant there.

{
    '$group': {
        _id: null,
        'Volume': {
            '$avg': '$Array.Volume'
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hello Tom, thanks for your answer! When I'm doing your way I receive - [ { _id: null, Volume: null } ] in console log.
add $ to your variable call - i edited the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.