【问题标题】:Count MongoDB collection row计数 MongoDB 集合行
【发布时间】:2013-08-03 14:46:58
【问题描述】:

我想知道如何计算我从 MongoDB 集合中获得的所有行数。

var collection = db.collection( _collection ).find();

现在我不知道里面有没有 somting,如果需要关注我从我的收藏中得到了多少行。

是否有更好的方法可以让我使用 Stream 函数将“数据”取出来?

var stream = collection.find().stream();            
stream.on("data", function(item)
{
    console.log(item.zipcode);
});

stream.on("end", function()
{
});

我怎样才能得到某种帮助,:)

【问题讨论】:

  • db.collection().find().count()?
  • 我已经尝试过了,但运气不佳...我想我可能会做一些破旧的事情 :)
  • 你在哪里做这个?
  • 当我使用 MongoDB 处理我的数据时,我正在尝试构建一个 Node.JS webservices 处理程序,但问题是我可以找出如何计算我的行数以获取一个错误:/

标签: node.js mongodb


【解决方案1】:

我根本没用过Node.JS驱动,但是看documentation,好像Collection()上面有count函数:

// Assuming DB has an open connection...
db.collection("my_collection", function(err, collection) {
    collection.count(function(err, count)) {
        // Assuming no errors, 'count' should have your answer
    }
});

这有帮助吗?

至于你问题的第二部分,我不完全确定你在问什么,但这里有几种获取数据的方法:

使用toArray() 函数为您提供所有文档的数组 (see docs):

collection.find().toArray(function(err, docs) {
    // 'docs' should contain an array of all your documents
    // 'docs.length' will give you the length of the array (how many docs)
});

使用each() 函数循环遍历结果并为每个结果执行给定的函数(see docs):

collection.find().each(function(err, doc) {
    // this function will be executed once per document

    console.log(doc.zipcode)
});

希望对你有所帮助。

【讨论】:

  • 这只有在他使用 node-mongodb-native 驱动时才有效。如果他使用的是Mongoose之类的包装器,则需要访问底层驱动才能使用toArrayeach
  • 这是真的。我做了他的假设,基于他指的是流函数(本机驱动程序具有)的事实,并且缺乏任何进一步的信息。
  • 非常感谢,“find().each(...) 函数解决了医学问题^^
猜你喜欢
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
  • 2014-11-30
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多