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

sch*_*ube 2 sorting mongodb

我面临这样的挑战:

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

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

map/reduce 是正确的方法吗?或者我应该专注于“计算领域”并使用这个。我对 MongoDB 比较陌生,我正在询问方向。

编辑:根据要求,这里有一些示例数据:

鉴于:

|     ID     | FieldA | FieldB | FieldC |
|------------|--------|--------|--------|
| Document 1 |     10 | X      |     40 |
| Document 2 |     20 | <null> |     50 |
| Document 3 |     30 | Z      |     60 |
Run Code Online (Sandbox Code Playgroud)

预期结果(订单)包括以计算作为注释的列

|     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 |
Run Code Online (Sandbox Code Playgroud)

谢谢你,舒贝

dni*_*ess 9

鉴于以下文件:

{ "a": 10, "b": "X",  "c" : 40 }
{ "a": 20, "b": null, "c" : 50 }
{ "a": 30, "b": "Z",  "c" : 60 }
Run Code Online (Sandbox Code Playgroud)

这样做的一种方法是这样的:

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
    }
})
Run Code Online (Sandbox Code Playgroud)

如果你有一个文件没有一个b领域,如:

{ "a": 20, "c" : 50 }
Run Code Online (Sandbox Code Playgroud)

那么你需要应用这里提到的技术之一。

所以你if在里面的部分$cond可能看起来像这样:

if: { $ne: [ "$b", undefined ] }, // whether "b" is null or doesn't exist at all
Run Code Online (Sandbox Code Playgroud)