我在MongoDB中使用聚合和拆分来标记字符串字段,它工作得很好。但我想对这个领域进行排序,由于某种原因,带有聚合的排序根本不起作用。
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我尝试了不同的分类方法,但它并没有像预期的那样工作。有人能帮忙吗?
发布于 2019-10-16 21:24:57
您可以按_id解压拆分、排序和分组,然后将排序拆分推送到数组中。
db.coll.aggregate([
{ $project: { split: {$split: ["$FIELD_NAME", " "] } } },
{$unwind: "$split"},
{$sort: {split: -1}},
{$group: {_id: "$_id", sorted_split: {$push: "$split"}}}
])https://stackoverflow.com/questions/58421007
复制相似问题