Amila Iddamalgoda
Amila Iddamalgoda

Reputation: 4286

How to retrive all userIds as a list from a collection in Mongodb + Express.js?

I'm using https://github.com/mongodb/node-mongodb-native?_ga=1.224176859.1706529023.1457418359 for my node.js project. And I need to get all the user ids (as a list) from the Mongo collection (user). Is it possible to do it from the given Mongo driver itself?

Here's my code:

MongoClient.connect(mongoUrl, function(err, db) {
          if (err) {
              throw err;
              return res.status(400).send(err);
          }

          db.collection('user').find({},{'password': false}).toArray(function(err, result) {
              if (err) {
                  throw err;
                  return res.status(400).send(err);
              }
              console.log(result);
              return res.status(200).send(result);
          });
      });

user collection

{
    "_id" : ObjectId("5789c80733118ab81b661160"),
    "username" : "",
    "firstName" : "Test",
    "lastName" : "",
    "userId" : 404040,
    "address" : "test address",
    "phoneNumber" : 1120202000,
    "isActive" : true,
    "subscriptionIdList" : [ 
        2220, 
        22252, 
        6526, 
        70505
    ],
    "password" : "",
    "createdAt" : "2016­06­21T11:22:11.089Z",
    "updatedAt" : "2016­07­21T11:22:11.089Z",
    "lastSubscribedAt" : ""
}

Upvotes: 1

Views: 321

Answers (2)

chridam
chridam

Reputation: 103355

A more elegant approach would be to simply use mongo's distinct method on the collection. This finds the distinct values for a specified field across a single collection and returns the results in an array.

The following shows how you can apply that to your case:

var collection = db.collection('user');

// Peform a distinct query against the userId field
collection.distinct('userId', function(err, result) {
    if (err) {
        throw err;
        return res.status(400).send(err);
    }
    console.log(result);
    return res.status(200).send(result);
});

Upvotes: 1

Patrick Roberts
Patrick Roberts

Reputation: 51836

Try using _.map():

var _ = require('lodash');

db.collection('user').find({}, {_id: 0, userId: 1}).toArray(function (err, result) {
  if (err) {
    throw err;
    return res.status(400).send(err);
  }
  var userIds = _.map(result, 'userId');
  console.log(userIds);
  return res.status(200).send(userIds);
});

After running npm install --save lodash on your project.

Upvotes: 1

Related Questions