【问题标题】:How to get collection's count in MongoDB?如何在 MongoDB 中获取集合的计数?
【发布时间】:2018-07-02 04:21:05
【问题描述】:

这是我的代码

var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/myDB');

myDB 中有集合users,如何获取users 中的文档数量?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

你自己尝试过吗?

不过如此,

db.open (function(error){
    db.collection("users", function(error, collection){
        collection.count({}, function(error, numOfDocs) {
            console.log(numOfDocs + ' total users');
        });
    });
});

这应该让你开始,我还没有测试过这段代码,但我记得是这样做的。

【讨论】:

  • 我试过了,我不明白你的代码,但它有效。你能留下关于count 的文档的链接吗?
  • 好的,我们开始吧,MongooseMongoDB 只是为了给你解释代码,db.open 打开到你的 MongoDB 数据库的连接。 db.collection('Users'...) 将选择用户集合,并在找到时返回集合变量中的集合。 collection.count,使用返回的集合来统计文档的数量,然后在 numOfDocs 中返回。
  • 但是我为什么要写那个呢?这是唯一的方法吗?如果我只想得到数字,我应该写这么大的代码吗?
  • @epsilon 因为您必须指示计算机要查找的内容。您可以查看管理数据库的工具,它可能会使查询更容易一些。
【解决方案2】:

试试这个方法,它是我的虚拟代码中的一个 sn-p,它应该可以工作

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/myDB');   // Connect to mongodb
mongoose.connection.once('open',(db)=>{         // opens the connection for us
    console.log("Connection made to mongodb");
    mongoose.model('<collection>').count().then((count) => { // replace <collection> with collection name
            console.log(count);
    })
}).on('error',(error)=>{
    console.log("connection error to mongodb : " + error);
}); 

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2016-12-15
    相关资源
    最近更新 更多