MongoDB 使用 distinct 查询

2 阅读1分钟

distinct 是 MongoDB 中一个有用的查询方法,用于返回指定字段的所有不同值数组。

基本语法

db.collection.distinct(field, query, options)

参数说明:

  • field:必需,要返回不同值的字段名
  • query:可选,使用查询操作符指定筛选条件
  • options:可选,额外的选项,如排序等

基本使用示例

1. 查找集合中某个字段的所有不同值

// 查找所有不同的用户名
db.users.distinct("username")

2. 带条件的 distinct 查询

// 查找年龄大于18的用户中所有不同的城市
db.users.distinct("city", { "age": { $gt: 18 } })

3. 在嵌套文档中使用 distinct

// 查找所有用户的地址中不同的邮编
db.users.distinct("address.zipCode")

4. 在数组字段中使用 distinct

// 查找所有用户拥有的不同标签
db.users.distinct("tags")

在 Node.js 应用中使用

// 使用 MongoDB Node.js 驱动
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
  const db = client.db("mydb");
  
  db.collection("users").distinct("city", function(err, result) {
    if (err) throw err;
    console.log(result);
    client.close();
  });
});

注意事项

  1. distinct 操作会对整个集合进行扫描,对于大型集合可能会影响性能
  2. 对结果进行索引可以提高查询效率:db.collection.createIndex({ "field": 1 })
  3. 在分片集群中,distinct 命令会将请求发送到所有分片,然后在主节点上合并结果

使用场景

  • 获取产品所有不同的类别
  • 查找系统中所有不同的用户角色
  • 获取所有不同的地理位置信息
  • 分析数据中的唯一值分布