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

MongoDB嵌套数组场景下使用$slice操作符失败问题咨询

你之前的写法不生效,是因为MongoDB的find投影不支持在$位置运算符匹配到的数组元素下嵌套使用$slice操作子数组,需要改用聚合管道实现,正确查询语句如下:

db.collection.aggregate([
  // 过滤符合条件的根文档
  {
    $match: {
      name: "admin",
      "datasets.name": "test"
    }
  },
  // 拆分datasets数组为单条元素
  {
    $unwind: "$datasets"
  },
  // 筛选出名称为test的dataset条目
  {
    $match: {
      "datasets.name": "test"
    }
  },
  // 按要求格式输出,对datapoints数组取前3位
  {
    $project: {
      _id: 0,
      name: "$datasets.name",
      datapoints: {
        $slice: ["$datasets.datapoints", 0, 3]
      }
    }
  }
])

执行后即可得到你期望的输出:{ name: "test", datapoints: [1,6,4] }。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:54:05