[英]MongoDB average aggregation using NodeJS
Good afternoon everyone.大家下午好。
I have an Array inside a MongoDB Document.我在 MongoDB 文档中有一个数组。 I wan't to find a
Volume
inside it and make an average for whole collection on Volume
parameter.我不想在其中找到一个
Volume
并在Volume
参数上对整个集合进行平均。
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.我将有很多相同类型的文档,我需要在
Volume
参数的每个文档之间进行平均计算。
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.以防万一我可以连接到数据库
username:password
,例如。
How I should specify it NodeJS?我应该如何指定它 NodeJS?
NodeJS Full Code 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);
});
}
);
}
Your $group
syntax is just wrong:您的
$group
语法是错误的:
Groups input documents by the specified _id expression and for each distinct grouping, outputs a documen
按指定的 _id 表达式对输入文档进行分组,对于每个不同的分组,输出一个文档
A $group
stage must have a _id
field specified. $group
阶段必须指定一个_id
字段。 to group the entire collection just put any constant there.对整个集合进行分组只需将任何常量放在那里。
{
'$group': {
_id: null,
'Volume': {
'$avg': '$Array.Volume'
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.