node.js 如何在 Mongoose 中查询不同的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6043847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:11:13  来源:igfitidea点击:

How do I query for distinct values in Mongoose?

mongodbnode.jsmongoose

提问by Kit Sunde

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?

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

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

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

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

However the resultsis 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 collectionsreturn if at all possible.

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

回答by Risadinha

Just to give an update for Mongoose 3.x:

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

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

回答by yshgt

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

通过 node.js v0.4.7,猫鼬 1.3.3

回答by Bryan

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.

我通读了源代码,node-mongodb-native 驱动程序是类的动力。所以在连接对象上。所以在你完成 mongoose.connect(mongodb://) 之后,你可以试一试。

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

  });
}