【问题标题】:How to find the length of strings (phrases) in mongodb and sort them according to length?如何在mongodb中查找字符串(短语)的长度并根据长度对其进行排序?
【发布时间】:2019-12-20 05:25:02
【问题描述】:

我已经尝试找到它完美工作的短语的长度,但是当我根据长度对其进行排序时,它会给出错误“$strLenCP 需要一个字符串参数,找到:int”。 我试过这个:https://stackoverflow.com/a/44161848 但它给出的错误如下:

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. 

是否有相同的解决方案?请给我建议。

【问题讨论】:

  • 您可能有一个integer 作为您的phrases 字段之一的值,请先尝试通过在$sort 之前附加$match 条件作为{ "phrases" : { $type : "string" } } 过滤文档。跨度>

标签: mongodb sorting


【解决方案1】:

您必须使用$toStringNumber 字段转换为String 字段... 你可以在MongoPlay Around Link查看工作演示

db.collection.aggregate([
  {
     $addFields: {
         phrases: {
           $toString: "$phrases"
         }
     }
  }, 
  {
     $project: {
         _id: 0,
         phrases: 1,
         length: {
            $strLenCP: "$phrases"
         }
     }
  },
  {
     $sort: {
       length: -1
     }
  }
])

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多