我有一个问题,我希望能够为一个集合获取所有独特的城市,我的代码如下所示:
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var PersonSchema = new Schema({
name: String,
born_in_city: String
});
var Person = mongoose.model('Person', PersonSchema);
在 native MongoDb 中,我可以执行 db.person.distinct("born_in_city")
,但似乎没有任何与 Mongoose 等效的东西。是否只有自己遍历所有文档才能做到这一点,还是有更好的解决方案?
为了尝试按照回答者的建议使用底层 node-mongodb-native
,我尝试这样做:
mongoose.connection.db.collections(function(err, collections){
collections[0].distinct('born_in_city', function( err, results ){
console.log( err, results );
});
});
但是 results
是空的并且没有错误。我还希望能够仅按名称获取所需的集合,而不是尽可能过滤 collections
返回的内容。
最佳答案
只是为 Mongoose 3.x 提供更新:
MyModel.find().distinct('_id', function(error, ids) {
// ids is an array of all ObjectIds
});
https://stackoverflow.com/questions/6043847/