英文:
Mongo sort by either of 2 fields
问题
我有一些文件,其中foo
字段始终嵌套在x
或y
中,而不是同时出现。
我想要按此字段排序并获取结果。
如果可以使用find().sort()
来实现,那将很好,但如果需要使用aggregate()
,也希望得到相关答案。
英文:
I have documents where the foo
field is always nested in x
or y
and not both.
{
"_id": ObjectId("5a6eb97b2937803b14255180"),
"x": {
"foo": 42
},
"y": { }
},
{
"_id": ObjectId("5a6eb97b2937803b14255181"),
"x": { },
"y": {
"foo": 24
}
}
I want to sort by it and get
{
"_id": ObjectId("5a6eb97b2937803b14255181"),
"x": { },
"y": {
"foo": 24
}
},
{
"_id": ObjectId("5a6eb97b2937803b14255180"),
"x": {
"foo": 42
},
"y": { }
}
It would be great if I can do it with find().sort()
and not aggregate()
, but an aggregate()
answer would be appriciated too.
答案1
得分: 1
使用$ifNull
创建一个排序键,如果x.foo
不存在,则回退到y.foo
,然后根据排序键进行排序。
db.collection.aggregate([
{
"$set": {
"sortKey": {
"$ifNull": [
"$x.foo",
"$y.foo"
]
}
}
},
{
$sort: {
sortKey: 1
}
},
{
"$unset": "sortKey"
}
])
英文:
Create a sort key with $ifNull
to fall back into y.foo
if x.foo
is not present then sort on the sort key.
db.collection.aggregate([
{
"$set": {
"sortKey": {
"$ifNull": [
"$x.foo",
"$y.foo"
]
}
}
},
{
$sort: {
sortKey: 1
}
},
{
"$unset": "sortKey"
}
])
Side note: It might be better if you can preprocess your documents and materialized a single sort key. You can then index the consolidated sort key to gain performance boost and simpler queries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论