簡體   English   中英

從同一貓鼬集合添加特定值-Node JS

[英]Add specific values from the same mongoose collection - node js

我用貓鼬創建了一個如下所示的集合:

 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調用,因此需要將其存儲為字符串,因此在將這些值加在一起之前是否必須先解析parseString?

所以我想要的最終結果是這樣的:

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

我看了一下聚合,但是我只使用一個集合,所以我認為這不適合我嗎? 任何幫助表示贊賞。

首先得到總數如下

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

聚合不能更改現有數據類型,因此在這種情況下,您應該使用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);
});

暫無
暫無

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

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