How do I query for distinct values in Mongoose?

Mongodbnode.jsMongoose

Mongodb Problem Overview


I have a problem where I want to be able to get all the unique cities for a collection, and my code looks something like this:

var mongoose = require("mongoose"),
Schema = mongoose.Schema;

var PersonSchema = new Schema({
    name: String,
    born_in_city: String
});
var Person = mongoose.model('Person', PersonSchema);

In native MongoDb I could just do db.person.distinct("born_in_city"), but there doesn't seem to be anything equivalent for Mongoose. Is the only option to iterate over all of the documents myself to do this, or is there a better solution?

In an attempt to use the underlying node-mongodb-native as suggested by the answerer I attempted to do this:

mongoose.connection.db.collections(function(err, collections){
  collections[0].distinct('born_in_city', function( err, results ){
    console.log( err, results );
  });
});

However the results is empty and there's no error. I would also prefer to be able to fetch only the needed collection by name rather than have to filter what collections return if at all possible.

Mongodb Solutions


Solution 1 - Mongodb

Just to give an update for Mongoose 3.x:

MyModel.find().distinct('_id', function(error, ids) {
    // ids is an array of all ObjectIds
});

Solution 2 - Mongodb

In my program, this code works.

Person.collection.distinct("born_in_city", function(error, results){
  console.log(results);
});

by node.js v0.4.7, mongoose 1.3.3

Solution 3 - Mongodb

I read through the source code and the node-mongodb-native driver is what powers the class. So on the connection object. So after you have done mongoose.connect(mongodb://), you can give this a shot.

if(mongoose.connections.length > 0) {
  var nativeconn = mongoose.connections[0].conn;
  nativeconn.person.distinct('born_in_city', function(error, results){
   
  });
}

Solution 4 - Mongodb

const findBornCity = async() => {
    const bornCity = await Person.find().distinct("born_in_city")
    return bornCity
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKit SundeView Question on Stackoverflow
Solution 1 - MongodbRisadinhaView Answer on Stackoverflow
Solution 2 - MongodbyshgtView Answer on Stackoverflow
Solution 3 - MongodbBryanView Answer on Stackoverflow
Solution 4 - MongodbManish ChoudharyView Answer on Stackoverflow