【发布时间】:2021-09-16 12:27:00
【问题描述】:
我想编写一个聚合管道,如果满足条件,我想在其中进行排序。如果条件不满足,那么我只想按原样退回文件。如何继续它? 我正在检查 has_presence 字段以决定是否对 name 字段上的文档进行排序的示例文档(每个文档将始终有一个 has_presence 字段):
案例一:
Input:
{
"name": "microsoft",
"has_presence": true
},
{
"name": "google",
"has_presence": true
}
Output:
{
"name": "google",
"has_presence": true
},
{
"name": "microsoft",
"has_presence": true
}
Explanation: has_presence is true, so sorted the output by name.
案例 2:
Input:
{
"name": "microsoft",
"has_presence": false
},
{
"name": "google",
"has_presence": false
}
Output:
{
"name": "microsoft",
"has_presence": false
},
{
"name": "google",
"has_presence": false
}
Explanation: has_presence is false, so kept the order as it is in output.
【问题讨论】:
-
你的情况如何?
-
问题是如何只对集合的一部分进行排序?为什么你需要这个?出于性能原因?还是您只想将旧职位保留在未排序的部分? ($自然排序)
-
不,我想根据文档中始终存在的字段对整个集合进行排序。为清楚起见,添加了示例说明。 @Takis_
-
好的,但是这 2 个集合始终为真或始终为假,如果在 1 个集合中有些是假的,有些是真的,会发生什么?或者这永远不会发生?
-
是的@Takis_,这永远不会发生
标签: mongodb mongodb-query aggregation-framework pymongo