只对现有字段sorting

我有这样的collections。 只有less数用户具有sortOrder字段

 [{ "_id": "59ccf78bde3d14019169c105", "name": "Best FX broker ", }, { "_id": "59ccf78bde3d14019169c102", "name": "Best automated Performance tool ", "sortOrder": 1, }, { "_id": "59ccf78bde3d14019169c104", "name": "Best Regtech/ reporting solution ", }, { "_id": "59ccf78bde3d14019169c106", "name": "NEW: BEST CRYPTO SERVICE PROVIDER", "sortOrder": 2, }] 

当我按sort({"sortOrder": 1})我得到这个

 [{ "_id": "59ccf78bde3d14019169c105", "name": "Best FX broker ", }, { "_id": "59ccf78bde3d14019169c104", "name": "Best Regtech/ reporting solution ", }, { "_id": "59ccf78bde3d14019169c102", "name": "Best automated Performance tool ", "sortOrder": 1, }, { "_id": "59ccf78bde3d14019169c106", "name": "NEW: BEST CRYPTO SERVICE PROVIDER", "sortOrder": 2, }] 

但我需要像这样sorting集合(顶部的字段sortOrder值)

 [ { "_id": "59ccf78bde3d14019169c102", "name": "Best automated Performance tool ", "sortOrder": 1, }, { "_id": "59ccf78bde3d14019169c106", "name": "NEW: BEST CRYPTO SERVICE PROVIDER", "sortOrder": 2, }, { "_id": "59ccf78bde3d14019169c105", "name": "Best FX broker ", }, { "_id": "59ccf78bde3d14019169c104", "name": "Best Regtech/ reporting solution ", }] 

我应该写什么查询来获得这个?

       

网上收集的解决方案 "只对现有字段sorting"

db.collection.aggregate([{$ project:{“_id”:1,“sortOrder”:1,“name”:1,“sortOrder”:{“$ ifNull”:[“$ sortOrder”,“”]} }},{$ sort:{sortOrder:1}}

])

您几乎可以使用callback来处理sorting。

虽然我的解决scheme是令人厌恶的低效率(对不起),它的工作原理:

 array.sort(function (a, b) { if (a.sortOrder == undefined && b.sortOrder == undefined) { return 0; } if (a.sortOrder == undefined) { return 1; } if (b.sortOrder == undefined) { return -1; } if (a.sortOrder > b.sortOrder) { return 1; } if (a.sortOrder < b.sortOrder) { return -1; } return 0; }); 

这里的a和bvariables是数组中的元素,这里返回-1将它移动到数组的前面,0不改变,1移回数组,如果这是有道理的。