mongodb-query - 使用 mongo shell 查找不同长度的字符串字段
问题描述
给定一个 mongo 集合,例如:
col1 col2
1 "mango"
2 "banana"
3 "watermelon"
4 "orange"
如何获取列 col2 的不同字符串长度的长度?它可能会使用 strLenCP 函数,但无法仅为投影构建它。
预期输出为:(5, 6, 10),因为 (banana, orange) 的不同字符串长度为 6,西瓜为 10,芒果为 5。
解决方案
您可以通过$strLenCP
在 a中使用聚合管道来执行此操作$group
:
db.test.aggregate([
// Group documents by their col2 string length
{$group: {_id: {$strLenCP: '$col2'}}}
])
输出:
{ "_id" : 10 }
{ "_id" : 6 }
{ "_id" : 5 }