簡體   English   中英

MongoDB 使用 NodeJS 的平均聚合

[英]MongoDB average aggregation using NodeJS

大家下午好。

我在 MongoDB 文檔中有一個數組。 我不想在其中找到一個Volume並在Volume參數上對整個集合進行平均。

MongoDB 內的文檔:

MongoDB 屏幕

如您所見,我在數組中有數組。 我將有很多相同類型的文檔,我需要在Volume參數的每個文檔之間進行平均計算。

有問題的代碼區域(這只是展示我的嘗試不起作用。

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);
            });
        }
    );
}

以防萬一我可以連接到數據庫username:password ,例如。

我應該如何指定它 NodeJS?

NodeJS 完整代碼

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);
            });
        }
    );
}

您的$group語法是錯誤的:

按指定的 _id 表達式對輸入文檔進行分組,對於每個不同的分組,輸出一個文檔

$group階段必須指定一個_id字段。 對整個集合進行分組只需將任何常量放在那里。

{
    '$group': {
        _id: null,
        'Volume': {
            '$avg': '$Array.Volume'
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM