首页 > 解决方案 > Mongodb - 在嵌套数组中只取一个元素

问题描述

我正在使用 mongodb 来存储我的数据。我的集合包含一个由类型标识的对象列表,以及每个对象的其他对象列表。

我收藏的一个例子是:

[
  {
    "type": "a",
    "properties": [
      {
        "value": "value_a",
        "date": "my_date_a"
      },
      {
        "value": "value_b",
        "date": "my_date_b"
      },
      ...
    ]
  },
  ...
]

基于上述数据结构,我想按给定类型检索所有集合,为每个集合只取嵌套数组中的一个元素(将嵌套列表减少为只有一个元素的列表)。

因此,给定类型“a”,结果示例可能是:

[
  {
    "type": "a",
    "properties": [
      {
        "value": "value_a",
        "date": "my_date_a"
      }
    ]
  },
  ...
]

我开始尝试这个查询{ "type": "a" }来过滤集合。但是,我怎么能只取一个“属性”元素呢?我不能使用“切片”运算符。

非常感谢。

标签: arraysmongodbfilternested

解决方案


我从您对 slice 的引用中假设您对匹配特定的嵌套元素不感兴趣,而只是在固定索引处获取一个值(例如,0)。

如果您愿意使用聚合管道,可以在投影中使用 arrayElementAt:

db.collection.aggregate([
    // matches documents with type 'a'
    { $match: { type: 'a' } }, 
    // creates a new document for each
    { $project: { 
        // that contains the original value for type
        type: 1, 
        // and the first element from the original properties for properties
        properties: { $arrayElemAt: [ "$properties", 0 ] } 
    } }
])

推荐阅读