Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

mongodb - How do I query for distinct values in Mongoose?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to give an update for Mongoose 3.x:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...