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.
To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.
The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.
MongoDB – Distinct() Method In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.
You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large.
Just to give an update for Mongoose 3.x:
MyModel.find().distinct('_id', function(error, ids) { // ids is an array of all ObjectIds });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With