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

MongoDB嵌套数组文档查询:如何仅返回匹配的数组元素

MongoDB如何只返回数组中匹配查询条件的元素?

问题描述

我在MongoDB中有如下结构的文档:

{
  "_id": ObjectId("62d3af6d0df67535575ee87e"),
  "time": "2022-07-17T09_39_19",
  "data": [
    {
      "Manufacturer": "iPollo",
      "Model": "V1",
      "Release": "June 2022",
      // 其余字段省略
    },
    {
      "Manufacturer": "Jasminer",
      "Model": "X4",
      "Release": "November 2021",
      // 其余字段省略
    }
  ]
}

当执行查询语句 db.collection.find({"data.Manufacturer":"iPollo"}) 时,会返回整个文档,包含data数组内的所有元素。我希望直接返回data数组中匹配Manufacturer: "iPollo"的对象,无需手动遍历整个数组。

解决方案

1. 使用$elemMatch投影(仅返回第一个匹配元素)

$elemMatch可以在投影阶段筛选出数组中第一个符合条件的元素:

db.collection.find(
  {"data.Manufacturer": "iPollo"},
  {"data": {$elemMatch: {"Manufacturer": "iPollo"}}, _id: 0, time: 0}
)

注意:此方法仅返回数组中第一个匹配的元素,若data数组存在多个Manufacturer为iPollo的对象,只会返回首个匹配项。

2. 使用聚合管道(返回所有匹配元素)

如果需要获取数组中所有符合条件的元素,聚合管道是更合适的选择:

db.collection.aggregate([
  // 匹配包含目标元素的文档
  {$match: {"data.Manufacturer": "iPollo"}},
  // 将data数组拆分为单个文档
  {$unwind: "$data"},
  // 筛选出符合条件的元素
  {$match: {"data.Manufacturer": "iPollo"}},
  // 可选:将结果重新组合为数组(按需使用)
  {$group: {_id: "$_id", matchedData: {$push: "$data"}}}
])

该方法会返回data数组中所有匹配Manufacturer: "iPollo"的元素,不受数量限制。

3. 使用$filter(MongoDB 3.2+,简洁高效)

$filter支持在投影阶段直接过滤数组,返回所有匹配元素,无需拆分文档:

db.collection.find(
  {"data.Manufacturer": "iPollo"},
  {
    _id: 0,
    time: 0,
    matchedData: {
      $filter: {
        input: "$data",
        as: "item",
        cond: {$eq: ["$$item.Manufacturer", "iPollo"]}
      }
    }
  }
)

此方法最为简洁,结果会被封装在matchedData字段中,包含所有符合条件的data元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:06:32