如何在Mongodb中计算字符串字符

时间:2019-03-31 02:54:55

标签: mongodb mongodb-query aggregation-framework

我试图弄清楚如何计算字符串值中的字符数而不将空格作为计数。例如,我希望“ Honda Civic”返回10的长度,这不计算本田和Civic之间的间隔。

#include <iostream>
#include <ifstream>


using namespace std;

double trapInt(const double xvals[], const double yvals[], int nElements);


int main()
{
const int MAX_SIZE = 101;
double xData[MAX_SIZE];
double yData[MAX_SIZE];

ifstream infile("trapezoidData.txt");
if(infile.fail())
  {
    for(int a=0; a<MAX_SIZE; ++a)
    {
      infile >> xData[a] >> yData[a];
      cout << xData[a] << '\t' << yData[a] << endl;
  }

}
else
{
  cout << "Could not open infile." << endl;
}

cout.setf(ios::fixed);
cout.precision(3);

return 0;
}

结果:carNameLength:10

1 个答案:

答案 0 :(得分:0)

您可以在框架内使用$split$strLenCP来查找字符串(名称)的长度而没有空格。

您需要先用space(“”)分割名称,然后将所有字符串的长度加起来。

尝试一下:

db.cars.aggregate([{
    $match : { //add your match criteria here, or you can skip this part}
},{
    $project : {
        name : 1,
        name_array : { $split : {$name : " "}} //split the name with space and store the result in name_array
    }
},{
    //unwind the array, so that we can store each string length 
    $unwind : "$name_array"
},{
    $project : {
        name : 1,
        nameLength : {$strLenCP : $name_array}
    }
},{
    $group :{
        _id : "$_id",
        name : {$first : "$name"},
        carNameLength : {$sum : "$nameLength"}//add all the string length
    }
}])

$split documentation$strLenCP documentation上了解更多详细信息。