查找 MongoDB 字符串数组中最长的项

问题描述 投票:0回答:1

A 在 MongoDB 中有一个集合 Products

{
  "name": "My Product 01",
  "description": "This is an excelent product", 
  "tags": [
    "AA",
    "BBBB",
    "C",
    "DDDDDDDDDDD"
  ]  
}

如何找到该集合内所有对象的标签数组中最长的字符串? (如果我只有这个对象,最长的项目将是“DDDDDDDDDDD”,有 11 个字符)。

arrays string mongodb nosql-aggregation
1个回答
0
投票

您可以在聚合管道中的数组上运行

$reduce

这是一个示例,我创建了一个名为

longestTag
的新字段,其中包含长度和标签名称字段。您可以将项目字段和格式添加到所需的结构中。这与 javascript reduce 非常相似。
initialValue
将是存储迭代之间结果的累加器

db.collection.aggregate([
  {
    $addFields: {
      longestTag: {
        $reduce: {
          input: "$tags",
          initialValue: { tag: "", length: 0 },
          in: {
            $cond: {
              if: { $gt: [{ $strLenCP: "$$this" }, "$$value.length"] },
              then: { tag: "$$this", length: { $strLenCP: "$$this" } },
              else: "$$value"
            }
          }
        }
      }
    }
  }
])

https://mongoplayground.net/p/ZCoQVKG6LRI

© www.soinside.com 2019 - 2024. All rights reserved.