使用mongo shell查找不同长度的字符串字段

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

鉴于mongo集合,如:

col1   col2
1      "mango"
2      "banana"
3      "watermelon"
4      "orange"

如何获得列col2的不同字符串长度的长度?它可能会使用strLenCP函数,但我不能仅为投影构造它。

预期的产量将是:(5,6,10),因为(香蕉,橙子)的不同串长度为6,西瓜10和芒果5。

mongodb-query mongo-shell
1个回答
1
投票

您可以使用$strLenCP中的$group通过聚合管道执行此操作:

db.test.aggregate([
    // Group documents by their col2 string length
    {$group: {_id: {$strLenCP: '$col2'}}}
])

输出:

{ "_id" : 10 }
{ "_id" : 6 }
{ "_id" : 5 }
© www.soinside.com 2019 - 2024. All rights reserved.