从同一个猫鼬集合 - node js 中添加特定值

Add specific values from the same mongoose collection - node js

本文关键字:添加 js node 同一个 集合      更新时间:2023-09-26

我在猫鼬中创建了一个集合,如下所示:

 db.myservers.find()
{ "_id" : ObjectId("5783a416c9"), "text_usage" : "15", "name" : "A1", "__v" : 0 }
{ "_id" : ObjectId("57831216c9"), "text_usage" : "220", "name" : "A2", "__v" : 0 }
{ "_id" : ObjectId("5783a41asd"), "text_usage" : "100", "name" : "A3", "__v" : 0 }

我的模式工作是这样的:

var serverSchema = new Schema({
    name: String,
    text_usage: String
  })
var myServer = mongoose.model('MyServer', serverchema)

我想将text_usage中的所有值相加并除以此列表中的对象数量 - 所以基本上找到一个平均值。但是,我的text_usage需要存储为字符串,因为它来自 API 调用,那么在将值相加之前我是否必须解析字符串?

所以我想要的最终结果是这样的:

var totalTextCount = 335;
var objectCount = 3;
var average = 111.66

看了一下聚合,但我只处理一个集合,所以我认为这不适合我?任何帮助,不胜感激。

聚合不能更改现有数据类型,因此在这种情况下,您应该使用 find 并遍历所有数据来获取总计、计数和平均值,例如:

var totalTextCount = 0, average = 0, objectCount = 0;
MyServer.find().lean().exec(function(err, datas) {
  datas.forEach(function(data) {
    totalTextCount += parseInt(data.text_usage);
    objectCount+= 1;
  }); 
  average = totalTextCount / objectCount;
  console.log(totalTextCount, objectCount, average);
});

首先得到总数

如下
Model =db.model('ServerList', serverSchema);        
var userCount = serverModel.count('name');

然后遍历所有记录以查找总计

   var total =0;
 serverModel.find(function (err, servers) {
  if (err) return console.error(err);
       servers.forEach(function(server){
       total += parseInt(server.text_usage);
       });
 })