-1

I need get amount of documents in db (mongodb) . I tried get this value to my var like this:

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

and like this:

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

But when I try to see this number in console, that show me 'undefined' :/ Whats wrong?
P.S sry for my english

YakutD
  • 75
  • 5

2 Answers2

1

From the docs. It's db.collection.count. Don't use find.

Returns the count of documents that would match a find() query for the collection or view. The db.collection.count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

Example Usage:

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);
  });
});

Here is a basic example of how count might work. I assume you are using the mongodb npm and not mongoose or other mongo wrappers like it. The way I would use this in a project is by making the connection to your mongodb its own module so that it can be reused with other queries. That way you don't have to wrap every query with a connection.

Max Baldwin
  • 3,404
  • 3
  • 26
  • 40
  • That's true of the general function, however you missed the "nodejs" tag on the question, so there's a different reason this does not return a result. Also the "count" thing has been answered before. – Neil Lunn May 23 '18 at 01:14
  • @NeilLunn the methods in the mongodb driver npm are the same as the methods that are used in the native mongodb shell. Therefore, this works. – Max Baldwin May 23 '18 at 14:56
  • The "methods" are, but awaiting the result of an :"async function" is not. Which is why it does not. – Neil Lunn May 23 '18 at 15:13
  • excuse me, can u pls tell me how I can wait result of async func? – YakutD May 23 '18 at 20:16
  • @YakutD I provided an example above – Max Baldwin May 23 '18 at 20:49
0

If you want to get all the docs of a collection, use:

db.collection.count

If you want to get all the docs of a collection by a field, use:

collection.find({email: email}).toArray(function (err, items) {
    console.log(items.length);
})
giankotarola
  • 765
  • 7
  • 13