You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询:用GroupBy与First实现CountryCode和CountryName去重

MongoDB 聚合实现按CountryCode去重并返回唯一语言条目

直接通过MongoDB聚合框架在数据库层完成过滤、分组去重和字段映射,避免客户端内存处理,提升查询效率。

1. MongoDB Shell 执行代码

db.TranslationObject.aggregate([
  // 过滤CountryCode和CountryName非空的文档
  {
    $match: {
      CountryCode: { $ne: null, $exists: true },
      CountryName: { $ne: null, $exists: true }
    }
  },
  // 按CountryCode分组,取每组首个文档的CountryName
  {
    $group: {
      _id: "$CountryCode",
      CountryName: { $first: "$CountryName" }
    }
  },
  // 映射字段结构,返回符合Language对象的结果
  {
    $project: {
      _id: 0,
      CountryCode: "$_id",
      CountryName: 1
    }
  }
])

2. .NET MongoDB 驱动代码示例

如果使用.NET驱动,可参考以下实现(假设已获取IMongoCollection<TranslationObject>实例):

var pipeline = new BsonDocument[]
{
    // 过滤非空字段
    new BsonDocument("$match", new BsonDocument
    {
        { "CountryCode", new BsonDocument("$ne", BsonNull.Value) { { "$exists", true } } },
        { "CountryName", new BsonDocument("$ne", BsonNull.Value) { { "$exists", true } } }
    }),
    // 按CountryCode分组并取首个CountryName
    new BsonDocument("$group", new BsonDocument
    {
        { "_id", "$CountryCode" },
        { "CountryName", new BsonDocument("$first", "$CountryName") }
    }),
    // 转换为Language对象结构
    new BsonDocument("$project", new BsonDocument
    {
        { "_id", 0 },
        { "CountryCode", "$_id" },
        { "CountryName", 1 }
    })
};

var result = await collection.Aggregate<Language>(pipeline).ToListAsync();

注:Language类需包含CountryCode和CountryName两个对应属性

关键说明

  • $match阶段先过滤无效数据,减少后续分组处理的数据量
  • $group阶段以CountryCode为分组键,$first会保留每组中第一个匹配到的CountryName(文档顺序默认按存储顺序,若需指定排序规则,可在$match后添加$sort阶段)
  • $project阶段调整输出结构,移除默认的_id字段,将分组键映射回CountryCode,最终结果直接匹配所需的Language对象结构

内容的提问来源于stack exchange,提问作者Lars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:10:15