我在mongodb数据库中的得分集(学生)数据库中有2个文档.
{
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' }
] }
Run Code Online (Sandbox Code Playgroud)
如何构造查询以获得以下结果
{
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' }
]
}
Run Code Online (Sandbox Code Playgroud)
即:基于时间查找文档的查询,必须按2个标准对结果进行排序
您可以使用cursor.sort()同时对多个字段(基本上是一个组合)进行排序,但我认为在同时对文档和子文档字段进行排序时它不起作用.如果您要对顶部文档的两个不同字段或子文档的两个不同字段进行排序,那么我猜它会没问题.
因此,您可以使用聚合框架获得类似的输出.所有你需要做的就是打破subs字段的数组,然后对它们进行排序.
你可以这样做:
db.col.aggregate({$unwind:'subs'}, {$sort:{id:1,'subs.time':1}});
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,你应该得到类似于这样的输出:
{
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' }
}
Run Code Online (Sandbox Code Playgroud)
Aru*_*n K -2
您可以使用cursor.sort(sort)
例如:
db.collection.find().sort( { 'id': 1 } )
Run Code Online (Sandbox Code Playgroud)
使用 id 按升序对结果进行排序。
有关更多详细信息,请参阅以下链接。 http://docs.mongodb.org/manual/reference/method/cursor.sort/