【问题标题】:Query live data from large MongoDB collection - Nodejs从大型 MongoDB 集合中查询实时数据 - Nodejs
【发布时间】:2017-09-22 05:41:31
【问题描述】:

我想获取最近 10 条记录和刚刚添加的最新记录。 我尝试使用可尾游标,但它花了我太多时间,因为它必须在到达集合结束之前扫描整个集合以等待数据。

{
    "_id" : ObjectId("56fe349d0ef0edb520f0ca29"),
    "topic" : "IoTeam/messages/",
    "payload" : "20:15:04:01:12:75,-127.00,679",
    "qos" : 0,
    "retain" : false,
    "_msgid" : "45975d0d.ba68a4",
    "mac" : "20:15:04:01:12:75",
    "temp" : "-127.00",
    "hum" : "679",
    "time" : "01/04/2016 15:43:09"
}

感谢您的帮助。

【问题讨论】:

  • 您可以做很多事情来帮助提高 mongodb 性能,但如果没有更多信息,我们将无能为力。发布您的架构设计,以及您到底想做什么,然后提供建议会更容易。
  • 嗨。谢谢你的回答。
  • 我要查询最后10条记录和实时数据记录。使用可尾游标时,小集合很好,但对于大集合(大约 20000 条记录),可尾游标从第一条记录扫描到最后一条记录需要太多时间。 {“_id”:ObjectId(“56fe349d0ef0edb520f0ca29”),“topic”:“IoTeam/messages/”,“payload”:“20:15:04:01:12:75,-127.00,679”,“qos”: 0,“保留”:假,“_msgid”:“45975d0d.ba68a4”,“mac”:“20:15:04:01:12:75”,“temp”:“-127.00”,“hum”:“ 679", "时间" : "01/04/2016 15:43:09" }
  • 您查询的是哪个字段?
  • @Ajmera: 我想查询字段_id

标签: node.js mongodb large-data


【解决方案1】:

如果不了解更多信息,仍然很难说出最佳解决方案。但这里有一个你可以尝试的建议(全部使用 mongo shell)

在时间键上创建索引。

db.your_collection_name.createIndex({time:-1})

创建索引后,键入以下内容以确保正确完成。

db.your_collection_name.getIndexes()

这将列出您的索引,您应该会看到为时间键添加了一个新索引。

警告:虽然这会减少查询时间键所需的时间,但会增加将新记录插入数据库所需的时间。这是因为新的插入需要被索引。因此,在扩展您的应用程序时要考虑到这一点,这可能意味着您将希望以不同的方式处理此问题。

【讨论】:

【解决方案2】:

首先,在字段time上创建索引。

db.collection('nameOfYourCollection')
  .createIndex(
      { "time": -1 },
      null,
      function(err, results){
          console.log(results);
      });

这将在您的集合的time 字段上创建一个索引。这可能需要一些时间。但是一旦创建了索引,查询就会快很多。

在您的查询之后执行此操作:

var cursor = db.collection('nameOfYourCollection').find().sort([ ["time", -1] ]).limit(10);
cursor.forEach(function(doc){
    if(doc) console.log("Got the document as : " + JSON.stringify(doc));
}, function(err){
    if(err) console.log("Error: " + JSON.stringify(err));
});

这将为您提供插入到集合中的最后 10 条记录。

您也可以在cursor 中调用toArray 而不是forEach。像这样的东西:

var cursor = db.collection('nameOfYourCollection').find().sort([ ["time", -1] ]).limit(10);
cursor.toArray(function(err, docs){
    if(err) console.log("Error: " + JSON.stringify(err));
    if(docs){
        console.log("Got the document as : " + JSON.stringify(docs));
        console.log("This is the latest record that was inserted : " + JSON.stringify(docs[0]));
    }
});

希望这会有所帮助。

【讨论】:

  • 我还需要实时跟踪插入的新记录
猜你喜欢
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多