我有这样的集合。
只有少数用户拥有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,
}]
但是我需要像这样排序集合(顶部有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 ",
}]
我应该写什么查询才能得到这个?
答案 0 :(得分:1)
db.collection.aggregate([ {$ project:{“_ id”:1,“sortOrder”:1,“name”:1,“sortOrder”:{“$ ifNull”:[“$ sortOrder”,“”]}}}, {$ sort:{sortOrder:1}}
])
答案 1 :(得分:0)
您可以使用回调几乎以任何方式处理排序。
虽然我的解决方案令人作呕的效率很低(抱歉),但它确实有效:
null
这里的a和b变量是数组中的元素,这里返回-1将它移动到数组的前面,0不会改变,1将它移回数组,如果这是有道理的。