我正在使用MongoDB。这是我的文件。集合名称为test
{"group_id":"111","image":"x1.jpg",create_time:129}
{"group_id":"111","image":"x2.jpg",create_time:94}
{"group_id":"222","image":"x3.jpg",create_time:129}
{"group_id":"222","image":"x4.jpg",create_time:101}
预期输出的示例
{"group_id":"111","count":2,"image":["x1.jpg","x2.jpg"]}
{"group_id":"222","count":2,"image":["x3.jpg","x4.jpg"]}
然后我尝试
db.test.aggregate([{"$group":{"_id":{"group_id":"$group_id"},"count":{"$sum":1},"image":{"$push":"$image"}}},{"$sort":{"count":1}}],{allowDiskUse:true})
但是我想得到图像按create_time排序的结果。像这样:
{"group_id":"111","count":2,"image":["x2.jpg","x1.jpg"]}
{"group_id":"222","count":2,"image":["x4.jpg","x3.jpg"]}
任何人都可以指导我进行分组依据和排序的正确组合吗?
答案 0 :(得分:1)
再使用一种
{'$ sort':{“ group_id”:1,“ image”:1}}
在聚合管道的开头
db.test.aggregate([
{'$sort' : {"group_id" : 1,"image" : 1}},
{"$group":{"_id":{"group_id":"$group_id"},"count":{"$sum":1},"image":{"$push":"$image"}}},
{"$sort":{"count":1}}],
{allowDiskUse:true})
希望您会得到预期的结果