如果字段B!= null,则按字段A排序MongoDB,否则按字段C排序

时间:2019-02-21 15:30:54

标签: mongodb sorting

我面临这个挑战:

检索按字段A排序的文档如果字段B存在/不为空否则按字段C排序。

在SQL世界中,我将执行两个查询并创建一个UNION SELECT,但我不知道如何从Mongo开始。

地图/路线减少了吗?还是我应该专注于“计算字段”并使用它。我对MongoDB相对较新,正在寻求指导。

编辑:根据要求提供一些示例数据:

给出:

|     ID     | FieldA | FieldB | FieldC |
|------------|--------|--------|--------|
| Document 1 |     10 | X      |     40 |
| Document 2 |     20 | <null> |     50 |
| Document 3 |     30 | Z      |     60 |

预期结果(顺序),包括以计算为注释的列

|     ID     | FieldA | FieldB | FieldC | "A" if "B" !=<null> else "C" |
|------------|--------|--------|--------|------------------------------|
| Document 1 |     10 | X      |     40 |                           10 |
| Document 3 |     30 | Z      |     60 |                           30 |
| Document 2 |     20 | <null> |     50 |                           50 |

谢谢你, 舒伯

1 个答案:

答案 0 :(得分:2)

提供以下文件:

    <td><a href="view_messagesearch?themeid=id"><?php echo $row ['theme'];?></a></td>

一种方法是这样的:

{ "a": 10, "b": "X",  "c" : 40 }
{ "a": 20, "b": null, "c" : 50 }
{ "a": 30, "b": "Z",  "c" : 60 }

如果您的文档没有,则db.collection.aggregate({ $addFields: { "sortField": { // create a new field called "sortField" $cond: { // and assign a value that depends on if: { $ne: [ "$b", null ] }, // whether "b" is not null then: "$a", // in which case our field shall hold the value of "a" else: "$c" // or else it shall hold the value of "c" } } } }, { $sort: { "sortField": 1 // sort by our computed field } }, { $project: { "sortField": 0 // remove "sort" field if needed } }) 字段如下:

b

然后您需要应用here中提到的一种技术。

因此,您在{ "a": 20, "c" : 50 } 中的if部分可以例如看起来像这样:

$cond
相关问题