【问题标题】:group base on array element mongoDB基于数组元素 mongoDB 的组
【发布时间】:2021-11-08 16:37:10
【问题描述】:

说明:我们如何根据数组元素进行分组,我想根据两个数组的0元素进行分组。

{
  "st": [
    [
      "2011-01-04T12:18:41Z",
      0
    ],
    [
      "2011-01-04T15:00:00Z",
      0
    ]
  ],
  "en": [
    [
      "2011-01-04T14:59:50Z",
      1
    ],
    [
      "2011-01-04T15:05:00Z",
      4
    ]
  ]
}

预期的输出文档看起来像。例如

[
  {
    "st": "2011-01-04T12:18:41Z",
    "en": "2011-01-04T14:59:50Z",
    "st_val": 0,
    "en_val": 1,
    "total_index_count": 2
  }, 
  {
    "st": "2011-01-04T15:00:00Z",
    "en": "2011-01-04T15:05:00Z",
    "st_val": 0,
    "en_val": 4,
    "total_index_count": 2
  }
]

【问题讨论】:

  • 你能再添加一个更复杂的例子吗?我不确定我是否理解。您是否只想将st 中的索引ien 数组中的索引i 匹配?
  • 是的,我想将它们两个索引i 合并为一个文档。
  • 它非常类似于 this 映射索引和合并对象。

标签: arrays mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以通过几种不同的方式执行此操作,这是一种利用 $map$arrayElemAt 运算符的方法。

db.collection.aggregate([
  {
    "$project": {
      elements: {
        $map: {
          input: {
            $range: [
              0,
              {
                $size: "$st"
              }
            ]
          },
          in: {
            st_val: {
              "$arrayElemAt": [
                {
                  "$arrayElemAt": [
                    "$st",
                    "$$this"
                  ]
                },
                0
              ]
            },
            st: {
              "$arrayElemAt": [
                {
                  "$arrayElemAt": [
                    "$st",
                    "$$this"
                  ]
                },
                1
              ]
            },
            en_val: {
              "$arrayElemAt": [
                {
                  "$arrayElemAt": [
                    "$en",
                    "$$this"
                  ]
                },
                0
              ]
            },
            en: {
              "$arrayElemAt": [
                {
                  "$arrayElemAt": [
                    "$en",
                    "$$this"
                  ]
                },
                1
              ]
            },
            
          }
        }
      }
    }
  },
  {
    $unwind: "$elements"
  },
  {
    $replaceRoot: {
      newRoot: "$elements"
    }
  }
])

Mongo Playground

【讨论】:

  • 看起来不错,我有 2 个问题。 1.在project阶段我们如何计算数组total_index_count缺失的索引。 2.在`"$range":[0,{"$size":"$st"}]`你为什么拿st为什么不en
  • 假设它们的长度相同,如果不是,您应该指定您期望的行为。
  • 我不确定total_index_count 是什么,因为在您指定的结果中它们都是2
  • sten 两个索引始终相等。比如st有2个索引,en应该是2个索引,那么project阶段的索引怎么算,那我们就需要小组赛?
猜你喜欢
  • 2022-08-23
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 2021-12-22
相关资源
最近更新 更多