Mongodb很新,我正在尝试使用Mongoose构建一个查询,以获得所需的结果,如果可能的话。
测试数据:
{ id: 1, display_time: '01:00', name: 'test1' },
{ id: 2, display_time: '03:00', name: 'test2' },
{ id: 3, display_time: '01:00', name: 'test3' },
{ id: 4, display_time: '04:00', name: 'test4' },
{ id: 5, display_time: '01:00', name: 'test5' }
期望的结果:
{
"01:00": [
{ id: 1, display_time: '01:00', name: 'test1' },
{ id: 3, display_time: '01:00', name: 'test3' },
{ id: 5, display_time: '01:00', name: 'test5' }
],
"03:00": [
{ id: 2, display_time: '03:00', name: 'test2' }
],
"04:00": [
{ id: 4, display_time: '04:00', name: 'test4' }
],
}
基本上,它根据display_time
字段对文档进行分组,并以该格式返回。这可能与Mongo有关吗?
答案 0 :(得分:1)
您可以尝试这样的事情:
db.collection.aggregate(
[
{ $group : { _id : "$display_time", test: { $push: "$$ROOT" } } }
]
)
{
"_id" : "01:00",
"test" :
[
{ id: 1, display_time: '01:00', name: 'test1' },
{ id: 3, display_time: '01:00', name: 'test3' }
]
}
{
"_id" : "04:00",
"test" :
[
{ id: 4, display_time: '04:00', name: 'test4' }
]
}
了解更多信息http://docs.mongodb.org/manual/reference/operator/aggregation/group/