乐闻世界logo
搜索文章和话题

How do i query for distinct values in mongoose

5 个月前提问
3 个月前修改
浏览次数77

6个答案

1
2
3
4
5
6

在Mongoose中,如果你想查询独特不重复的值,可以使用distinct方法。这个方法会在特定的文档集合中,对指定字段进行去重处理,并返回所有独特不重复的值。

以下是使用distinct方法的一个例子:

假设你有一个名为User的模型,模型中有一个字段叫email,你想要查询所有不重复的电子邮件地址。

javascript
const uniqueEmails = await User.distinct('email'); console.log(uniqueEmails);

这段代码会返回一个包含所有唯一电子邮件地址的数组。

如果你想对查询结果进一步筛选,例如只查询那些账户已经验证的用户的唯一电子邮件地址,可以在distinct方法中添加查询条件:

javascript
const uniqueVerifiedEmails = await User.distinct('email', { isVerified: true }); console.log(uniqueVerifiedEmails);

在这个例子中,distinct方法的第二个参数 { isVerified: true } 表示一个查询条件,它将返回字段email的不重复值,但只限于那些isVerified字段为true的文档。

使用distinct方法是在处理大数据集合时,以高效的方式查询独特值的一个很好的选择。但是请注意,性能会受到数据库索引配置的影响,因此,为了提高查询效率,相应字段上应该有合适的索引。

2024年6月29日 12:07 回复

Just to give an update for Mongoose 3.x:

shell
MyModel.find().distinct('_id', function(error, ids) { // ids is an array of all ObjectIds });
2024年6月29日 12:07 回复

In my program, this code works.

shell
Person.collection.distinct("born_in_city", function(error, results){ console.log(results); });

by node.js v0.4.7, mongoose 1.3.3

2024年6月29日 12:07 回复

const findBornCity = async() => { const bornCity = await Person.find().distinct("born_in_city") return bornCity }

2024年6月29日 12:07 回复

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.

shell
if(mongoose.connections.length > 0) { var nativeconn = mongoose.connections[0].conn; nativeconn.person.distinct('born_in_city', function(error, results){ }); }
2024年6月29日 12:07 回复

你的答案