Monday 5 June 2017

mongodb collection fetch information with criteria

Good evening

I'm facing the following issue:

I have this data in a collection in mongoDB

  { temperature: '25.9', _id: 5935a9175044472c8e60d5b7 },
  { temperature: '31.0', _id: 5935a9175044472c8e60d5b8 },
  { humidity: '45.2', _id: 5935a9175044472c8e60d5b9 },
  { humidity: '55.3', _id: 5935a9175044472c8e60d5ba }

I want to fetch it by type.

Can't find what I'm doin wrong in my code...

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
    numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
    numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});

Thank you so much for any help. Best regards.



via joarafa

No comments:

Post a Comment