简体   繁体   中英

MongoDB average aggregation using NodeJS

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 屏幕

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 Volume parameter.

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:password@ip.adress.port/<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);
            });
        }
    );
}

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'
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM