如何有效地连续查询mongodb数据库

时间:2019-04-15 02:49:39

标签: node.js mongodb

我是Node和MongoDB的新手,我有一个看似简单的请求。我设法连接到数据库,并使用查询来获得所需的结果。现在,我希望无限期地继续执行此查询,因为我项目的最终目标是实时绘制数据。

我本以为一个简单的'while(true)'循环就足够了,但事实并非如此。

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

// Connection URL
const url = 'mongodb://<username>:<password>@ds157614.mlab.com:57614/flight_data';


// Use connect method to connect to the Server
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {

  if (err) throw err;

  var dbo = db.db("flight_data").collection("data");

while(true)
{

    dbo.find().sort({_id: 1}).limit(1).toArray(function(err, result) {

    if (err) throw err;

    console.log("Temperature: " + result[0].data.temperature);

  });

}

db.close();

});

我发现while循环确实正在运行,但是由于某些原因,在while循环中时不会发生查询。如果删除while循环,则代码功能正常。我只希望它继续打印重复查询的结果。

1 个答案:

答案 0 :(得分:1)

连续查询数据库效率低下并且浪费资源,请改用change streams。它监视collection的任何更改,然后仅进行db调用。 仅适用于Mongo 3.6 +

const MongoClient = require("mongodb").MongoClient;

// Connection URL
const url =
  "mongodb://<username>:<password>@ds157614.mlab.com:57614/flight_data";

// Use connect method to connect to the Server
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
  if (err) throw err;

  const collection = db.collection("data");
  const changeStream = collection.watch();
  changeStream.on("change", next => {
    // process next document
    collection
      .find()
      .sort({ _id: 1 })
      .limit(1)
      .toArray(function(err, result) {
        if (err) throw err;

        console.log("Temperature: " + result[0].data.temperature);
      });
  });
  db.close();
});
相关问题