提问者:小点点

如何传递数组而不是必需的字符串节点


脚本逻辑-脚本从Binance API接收数据>; 然后我有聚合$avg来计算一个资产的平均值。 我将有一个以上的收集,所以我需要计算平均每个资产。

我有一个数组,用于存储MongoDB的集合名称。

const symbols = ["ADABTC", "AEBTC", "AIONBTC"]

我想从MongoDB集合中计算平均值。

const collection = db.collection(symbols);

这里-symbols对我不起作用,但是如果我简单地添加“adabtc”,那么它就起作用了,但是它不能解决我的问题,因为我想一个接一个地使用不同的集合名称。

如果要求数组是字符串,我如何传递它? 我需要使用1个以上的集合名称。

全码

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

// Connection URL
const url = 'mongodb://username:password@serveripadress:port/dbname?retryWrites=true&w=majority';
const symbols = ["ADABTC", "AEBTC", "AIONBTC"]
    // 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(symbols);
    collection.aggregate(
        [{
            '$group': {
                _id: null,
                'Volume': {
                    '$avg': '$Volume'
                }
            }
        }],
        function(err, cursor) {
            assert.equal(err, null);

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

共1个答案

匿名用户

不能将数组传递到请求字符串的函数中。 在您的示例中,您需要做的是join三个集合。 如果需要跨多个集合进行聚合,可以使用$lookup聚合管道运算符。 可以使用第一个集合进行连接:

db.collection(符号)=>; DB.Collection(符号[0])

然后修改查询以联接三个集合:

// Join with AEBTC collection
{
    $lookup:{
        from: symbols[1],       
        localField: //name of a value in first collection   
        foreignField: //name of same value in second collection
        as: //what you want to call it in the second table       
    }
},
{   $unwind: //what you called it },

// Join with AIONBTC collection
{
    $lookup:{
        from: symbols[2], 
        localField: //name of value in joined collections 1 and 2 
        foreignField: //name of that value in collection 3,
        as: //whatever you want to call it in the joined collection
    }
},
{   $unwind: //what you called it },

// define some conditions here 
{
    $match {}
},

// define which fields are you want to fetch
{   
    $group: {
            _id: null,
            'Volume': {
                '$avg': '$Volume'
    } 
}