在MongoDB中使用split后,如何对字段进行排序?

在MongoDB中使用split后,如何对字段进行排序?,mongodb,mongodb-query,Mongodb,Mongodb Query,我在MongoDB中使用aggregate和split对字符串字段进行标记,效果很好。但我想对字段进行排序,出于某种原因,使用聚合进行排序根本不起作用 db.coll.aggregate( { $project: { split: {$split: ["$FIELD_NAME", " "] } } } ) 它提供了以下输出: { "_id" : 112, "split" : [ "TOKEN", "EXCH" ] } { "_id" : 122, "split" : [ "TOKEN", "E

我在MongoDB中使用aggregate和split对字符串字段进行标记,效果很好。但我想对字段进行排序,出于某种原因,使用聚合进行排序根本不起作用

db.coll.aggregate( { $project: { split: {$split: ["$FIELD_NAME", " "] } } } )
它提供了以下输出:

{ "_id" : 112, "split" : [ "TOKEN", "EXCH" ] }
{ "_id" : 122, "split" : [ "TOKEN", "EXCH" ] }
{ "_id" : 332, "split" : [ "TOKN", "EXCH" ] }
{ "_id" : 444, "split" : [ "ABC", "IND", "INS" ] }
但是当我尝试对分割字段进行排序时,它会给我一个错误

db.table_a.aggregate( { $project: { split: {$split: ["$FIELD_NAME", " "] } } }, {$sort: {"split": -1}} )

2019-10-16T14:11:22.528-0500 E QUERY    [js] Error: command failed: {
    "ok" : 0,
    "errmsg" : "$split requires an expression that evaluates to a string as a first argument, found: int",
    "code" : 40085,
    "codeName" : "Location40085"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:534:17
assert.commandWorked@src/mongo/shell/assert.js:618:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12

我尝试了不同的排序方法,但效果不尽如人意。有人能帮忙吗

您可以展开拆分、排序,然后再次按id分组,将排序后的拆分推送到数组中

db.coll.aggregate([ 
 { $project: { split: {$split: ["$FIELD_NAME", " "] } } }, 
 {$unwind: "$split"}, 
 {$sort: {split: -1}}, 
 {$group: {_id: "$_id", sorted_split: {$push: "$split"}}} 
])

您要查询的文档的结构是什么?你能提供20份左右的文件样本,以便我们处理这些数据吗?