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

MongoDB聚合查询:匹配多字段与数组元素获取指定结果

修正MongoDB聚合查询以匹配指定条件并返回目标数组元素

你的核心需求是匹配文档级别的Id、Id1、Id2、collectionName字段,同时从List数组中筛选出指定name的元素并返回其countryId和name。之前的查询存在三个问题:未匹配全部文档条件、未过滤数组元素,且unwind的字段名错误。

方法一:使用$unwind+多阶段$match

db.country_admin.aggregate([
    // 1. 匹配文档级别的所有条件,提前过滤无关文档
    {
        $match: {
            "Id": "ObjectId(\"63e37afe7a3453d5014c0112\")",
            "Id1": "ObjectId(\"63e37afe7a3453d5014c0113\")",
            "Id2": "ObjectId(\"63e37afe7a3453d5014c0114\")",
            "collectionName": "Country",
            "List.name": "Afghanistan"
        }
    },
    // 2. 展开List数组,将每个数组元素转为独立文档
    { $unwind: "$List" },
    // 3. 过滤出数组中name匹配的元素
    {
        $match: {
            "List.name": "Afghanistan"
        }
    },
    // 4. 投影出需要的字段,调整为目标结构
    {
        $project: {
            _id: 0,
            countryId: "$List.countryId",
            name: "$List.name"
        }
    }
]).pretty()

方法二:使用$filter+$replaceRoot(无需展开数组)

如果数组元素较多,这种方法效率更高,避免拆分再过滤的额外开销:

db.country_admin.aggregate([
    // 匹配文档级别的所有条件
    {
        $match: {
            "Id": "ObjectId(\"63e37afe7a3453d5014c0112\")",
            "Id1": "ObjectId(\"63e37afe7a3453d5014c0113\")",
            "Id2": "ObjectId(\"63e37afe7a3453d5014c0114\")",
            "collectionName": "Country",
            "List.name": "Afghanistan"
        }
    },
    // 筛选List数组中符合条件的元素,取第一个匹配项
    {
        $project: {
            _id: 0,
            matchedCountry: {
                $first: {
                    $filter: {
                        input: "$List",
                        cond: { $eq: ["$$this.name", "Afghanistan"] }
                    }
                }
            }
        }
    },
    // 将匹配到的对象提升为顶层文档
    {
        $replaceRoot: { newRoot: "$matchedCountry" }
    }
]).pretty()

两种方法都能返回你期望的结果:

{
    "countryId" : 1,
    "name" : "Afghanistan"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:45:24