【问题标题】:I need get amount of documents in db (mongodb) [duplicate]我需要获取数据库中的文档数量(mongodb)[重复]
【发布时间】:2018-05-22 20:07:40
【问题描述】:

我需要在 db (mongodb) 中获取大量文档。我试着像这样把这个值传给我的变量:

var unique = collection.find({email: email}).count();

像这样:

var unique = collection.find({email: email}).toArray();
unique = unique.length;

但是当我尝试在控制台中查看这个数字时,它会显示“未定义”:/ 怎么了?
P.S 对不起我的英语

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    From the docs。这是db.collection.count。不要使用find

    返回匹配 find() 查询的文档数 收藏或查看。 db.collection.count() 方法不执行 find() 操作,而是计算并返回 匹配查询的结果。

    示例用法:

    const MongoClient = require('mongodb').MongoClient;
    // Connection url
    const url = 'mongodb://localhost:27017';
    // Database Name
    const dbName = 'users';
    // Connect using MongoClient
    MongoClient.connect(url, function(err, client) {
      const db = client.db(dbName);
      const email = 'foo@bar.com';
      const query = { email: email };
      const options = {};
    
      db.collection.count(query, options, (err, result) => {
        // handle error
        if (err) {
          console.log(err);
        }
        // do something with result
        console.log(result);
      });
    });
    

    这是count 可能如何工作的基本示例。我假设您使用的是 mongodb npm 而不是 mongoose 或其他类似的 mongo 包装器。我在项目中使用它的方法是将与您的 mongodb 的连接作为其自己的模块,以便它可以与其他查询重用。这样您就不必用连接包装每个查询。

    【讨论】:

    • 通用函数确实如此,但是您错过了问题上的“nodejs”标签,因此不返回结果的原因不同。之前也已经回答了“计数”的问题。
    • @NeilLunn mongodb 驱动程序 npm 中的方法与本机 mongodb shell 中使用的方法相同。因此,这是可行的。
    • “方法”是,但等待:“异步函数”的结果不是。这就是为什么它没有。
    • 对不起,你能告诉我如何等待异步函数的结果吗?
    • @YakutD 我在上面提供了一个例子
    【解决方案2】:

    如果要获取集合的所有文档,请使用:

    db.collection.count

    如果您想按字段获取集合的所有文档,请使用:

    collection.find({email: email}).toArray(function (err, items) {
        console.log(items.length);
    })
    

    【讨论】:

    • 但是我不能在功能之外使用这个数字:(
    • @YakutD 当然不能,是异步函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多