我正在尝试检索以下数据中每个object_name的最早创建日期和最近修改日期
{ "_id" : ObjectId("5a510666b2e543371cff44ef"), "object_name" : "A", "username" : "user1", "created_at" : ISODate("2018-01-06T17:24:54.026Z"), "last_modified" : ISODate("2018-01-06T17:24:54.026Z") }
{ "_id" : ObjectId("5a5106e7b2e543371cff4515"), "object_name" : "A", "username" : "user1", "created_at" : ISODate("2018-01-06T17:27:03.262Z"), "last_modified" : ISODate("2018-01-06T17:27:03.262Z") }
{ "_id" : ObjectId("5a510933b2e543371cff45be"), "object_name" : "B", "username" : "user1", "created_at" : ISODate("2018-01-06T17:36:51.300Z"), "last_modified" : ISODate("2018-01-06T17:36:51.300Z") }
{ "_id" : ObjectId("5a510939b2e543371cff45c5"), "object_name" : "C", "username" : "user2", "created_at" : ISODate("2018-01-06T17:36:57.058Z"), "last_modified" : ISODate("2018-01-06T17:36:57.058Z") }
使用以下管道
将每个用户名与不同的object_name分组没有问题pipeline := []bson.M{
{"$group": bson.M{"_id": "$username", "objects": bson.M{"$addToSet": "$object_name"}}},
}
但是,我还想为每个对象添加最早创建日期和最新修改日期。
这是我想要的输出:
[
{
"_id": "user1",
"objects": [
{
"object_name": "A",
"created_at": "2018-01-06T17:24:54.026Z",
"last_modified": "2018-01-06T17:27:03.262Z"
},
{
"object_name": "B",
"created_at": "2018-01-06T17:36:51.300Z",
"last_modified": "2018-01-06T17:36:51.300Z"
}
]
},
{
"_id": "user2",
"objects": [
{
"object_name": "C",
"created_at": "2018-01-06T17:36:57.058Z",
"last_modified": "2018-01-06T17:36:57.058Z"
}
]
}
]
我认为它与$ sort和$ first或$ last有关,但我不知道如何将它们放在一起。
答案 0 :(得分:1)
您可以尝试以下聚合查询。
db.colname.aggregate([
{"$group":{
"_id":{
"username":"$username",
"object_name":"$object_name"
},
"created_at":{"$min":"$created_at"},
"last_modified":{"$max":"$last_modified"}
}},
{"$group":{
"_id":"$_id.username",
"objects":{
"$push":{
"object_name":"$_id.object_name",
"created_at":"$created_at",
"last_modified":"$last_modified"
}
}
}}])