如何在 Mongoose 中查询不同的值? [英] How do I query for distinct values in Mongoose?

查看:46
本文介绍了如何在 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);

在原生 MongoDb 中,我可以只做 db.person.distinct("born_in_city"),但似乎没有任何与 Mongoose 等效的东西.是自己迭代所有文档来执行此操作的唯一选择,还是有更好的解决方案?

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?

为了按照回答者的建议使用底层 node-mongodb-native,我尝试这样做:

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 );
  });
});

然而 results 是空的,没有错误.我还希望能够仅按名称获取所需的集合,而不必尽可能过滤 collections 返回的内容.

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.

推荐答案

只是为了提供 Mongoose 3.x 的更新:

Just to give an update for Mongoose 3.x:

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

这篇关于如何在 Mongoose 中查询不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆