如何在mongodb中找到字符串(短语)的长度并根据长度对其进行排序?



我尝试过查找短语的长度,它可以完美地工作,但是当我根据长度对其进行排序时,它给出了错误"$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. 

有没有同样的解决方案?请建议我。

您必须使用$toStringNumber字段转换为String字段... 您可以在Mongo中查看工作演示播放链接

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

最新更新