我面临着这样的挑战:
如果字段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 |
预期结果(顺序),包括以计算作为注释的列
| 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 |
谢谢你,舒比
发布于 2019-02-22 04:10:04
给定以下文档:
{ "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
字段,如下所示:
{ "a": 20, "c" : 50 }
然后,您需要应用上述here中的一种技术。
因此,您在$cond
中的if
部件可能如下所示:
if: { $ne: [ "$b", undefined ] }, // whether "b" is null or doesn't exist at all
https://stackoverflow.com/questions/54810712
复制相似问题