0

I have tried finding the length of the phrases it works perfectly but when i sort it according to length it gives the error that "$strLenCP requires a string argument, found: int". I have tried this: https://stackoverflow.com/a/44161848 but it gives error as below:

db.abcd.aggregate({$project: {"phrases":1,"length": { $strLenCP: "$phrases" }}})

{ "_id" : ObjectId("5dfa08aceb51324106482d0b"), "phrases" : "the dupont safety management evaluation", "length" : 39 } 
{ "_id" : ObjectId("5dfa08aceb51324106482d0c"), "phrases" : "its factory sites", "length" : 17 } 
{ "_id" : ObjectId("5dfa08aceb51324106482d0d"), "phrases" : "dupont’s international standards", "length" : 32 } 
{ "_id" : ObjectId("5dfa08aceb51324106482d11"), "phrases" : "our safety systems winner", "length" : 25 } 
{ "_id" : ObjectId("5dfa08aceb51324106482d15"), "phrases" : "a stringent selection", "length" : 21 } 
{ "_id" : ObjectId("5dfa08aceb51324106482d16"), "phrases" : "rigorous evaluation process", "length" : 27 } 

db.abcd.aggregate([{$project: {"phrases":1,"length": { $strLenCP: "$phrases" }}},{$sort:{"length":-1}}])

2019-12-20T09:30:54.020+0530 E  QUERY    [js] uncaught exception: Error: command failed: { 

        "ok" : 0, 
        "errmsg" : "$strLenCP requires a string argument, found: int", 
        "code" : 34471, 
        "codeName" : "Location34471" 
}: aggregate failed. 

Is there any solution for the same? Please suggest me.

Simson
  • 3,373
  • 2
  • 24
  • 38
Explorer
  • 37
  • 6
  • You probably have an `integer` as value for one of your `phrases` field, try filtering the documents first by appending a `$match` condition as `{ "phrases" : { $type : "string" } }` before the `$sort`. – vikscool Dec 20 '19 at 05:52

1 Answers1

1

You have to convert Number field to String field using $toString... You can check working demo in MongoPlay Around Link

db.collection.aggregate([
  {
     $addFields: {
         phrases: {
           $toString: "$phrases"
         }
     }
  }, 
  {
     $project: {
         _id: 0,
         phrases: 1,
         length: {
            $strLenCP: "$phrases"
         }
     }
  },
  {
     $sort: {
       length: -1
     }
  }
])
Developer
  • 3,309
  • 2
  • 19
  • 23