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

MongoDB(Cosmos DB)查询数组中含指定属性的嵌入文档方案

你提到的三类查询需求均可通过MongoDB聚合管道实现,普通find方法的投影能力有限,无法满足复杂的数组过滤需求,以下是对应实现方案:

1. 返回包含os属性的最新嵌入文档完整内容

先过滤数组中所有带os属性的元素,再取过滤后数组的最后一项(即最新匹配的嵌入文档):

db.collection.aggregate([
  {
    $addFields: {
      // 过滤出所有包含os属性的report
      filteredReports: {
        $filter: {
          input: "$reports",
          cond: { $exists: ["$$this.os", true] }
        }
      }
    }
  },
  {
    $project: {
      computer: 1,
      // 取过滤后数组的最后一个元素,包装为数组符合返回格式要求
      reports: [{ $last: "$filteredReports" }],
      _id: 0 // 可选,不需要返回_id的话保留该行
    }
  }
])

2. 返回所有含os属性的嵌入文档,仅保留os字段,无空对象

先过滤无os属性的元素,再通过$map重构数组元素,仅保留os字段:

db.collection.aggregate([
  {
    $project: {
      computer: 1,
      reports: {
        $map: {
          input: {
            $filter: {
              input: "$reports",
              cond: { $exists: ["$$this.os", true] }
            }
          },
          in: { os: "$$this.os" }
        }
      },
      _id: 0 // 可选
    }
  }
])

3. 仅返回最新包含os属性的嵌入文档的os字段

结合前两个方案的逻辑,过滤后取最新元素的os字段即可:

db.collection.aggregate([
  {
    $addFields: {
      filteredReports: {
        $filter: {
          input: "$reports",
          cond: { $exists: ["$$this.os", true] }
        }
      }
    }
  },
  {
    $project: {
      computer: 1,
      reports: [
        { os: { $last: "$filteredReports.os" } }
      ],
      _id: 0 // 可选
    }
  }
])

注:以上语句在Cosmos DB的MongoDB API 3.6及以上版本均可以正常运行,无兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:57:01