如何根据子文档对mongodb查询结果进行排序 [英] How To Sort mongodb query results based on subdocuments
问题描述
我在 mongodb 数据库中的分数集合(学生)数据库中有 2 个文档,如下所示.
i am having 2 documents in score collections(student)databases like below in mongodb database.
{
id: 2,
type: 'newname',
subs: [
{ time: 20, val: 'b' },
{ time: 12, val: 'a' },
{ time: 30, val: 'c' }
] }, {
id: 1,
type: 'strs',
subs: [
{ time: 50, val: 'be' },
{ time: 1, val: 'ab' },
{ time: 20, val: 'cs' }
] }
如何构造查询以获得以下结果
How to construct a query to get the below result
{
id: 1,
type: 'strs',
subs: [
{ time: 1, val: 'ab' },
{ time: 20, val: 'cs' },
{ time: 50, val: 'be' }
]
},
{
id: 2,
type: 'newname',
subs: [
{ time: 12, val: 'a' },
{ time: 20, val: 'b' },
{ time: 30, val: 'c' }
]
}
即:根据时间查找文档的查询,并且必须根据 2 个条件对结果进行排序
ie: a query for find the documents based on time and have to sort the results on 2 criteria
- 按id ASC
- 按子文档时间 ASC
- by id ASC
- by sub document time ASC
推荐答案
您可以使用 cursor.sort()
同时对多个字段(基本上是一个组合)进行排序,但我不这样做不要认为它在同时对文档和子文档字段进行排序时有效.如果您要对顶部文档的两个不同字段或子文档的两个不同字段进行排序,那么我猜就可以了.
You can use cursor.sort()
to sort on multiple fields (basically a combo) at the same time but I don't think it works when sorting on both a document and a subdocument field at the same time.
If you were to sort on two different fields of the top document or on two different fields of a subdocument then it would be fine i guess.
因此您可以使用 aggregation 框架获得类似的输出.您所要做的基本上就是分解 subs
字段的数组,然后 排序.
So you can get a similar output using the aggregation framework. All you have to do is basically break down the arrays of the subs
field and then sort them.
你可以这样做:
db.col.aggregate({$unwind:'subs'}, {$sort:{id:1,'subs.time':1}});
使用上面的代码,你应该得到类似这样的输出:
With the above code you should get an output similar to this:
{
id: 1,
type: 'strs',
subs:
{ time: 1, val: 'ab' }
},{
id: 1,
type: 'strs',
subs:
{ time: 20, val: 'cs' }
},{
id: 1,
type: 'strs',
subs:
{ time: 50, val: 'be' }
},{
id: 2,
type: 'newname',
subs:
{ time: 12, val: 'a' }
},{
id: 2,
type: 'newname',
subs:
{ time: 20, val: 'b' }
},{
id: 2,
type: 'newname',
subs:
{ time: 30, val: 'c' }
}
这篇关于如何根据子文档对mongodb查询结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!