例如:-以下是“俱乐部”集合中的示例文档,
示例文档
{
"_id" : ObjectId("5cb8218ce2911e7c707e27fa"),
"name" : "name 1",
"members" : {
"user_1" : {
"created" : ISODate("2019-04-18T07:04:44.748Z"),
"lastActive" : 1555584757282,
"state" : 1,
"unreadMessages" : 0,
"userId" : "user_1_id"
},
"user_2" : {
"lastActive" : 1555588409686,
"state" : 1,
"unreadMessages" : 0,
"userId" : "user_2_id"
}
}
}
Mongo DB查询应返回以下字段:-
所需的输出-
{
{
"_id" : ObjectId("5cb8218ce2911e7c707e27fa"),
"name" : "name 1",
"members" : {
"user_1" : {
"lastActive" : 1555584757282
},
"user_2" : {
"lastActive" : 1555588409686
}
}
}
}
答案 0 :(得分:1)
您可以使用以下汇总
db.collection.aggregate([
{ "$addFields": {
"members": {
"$arrayToObject": {
"$map": {
"input": { "$objectToArray": "$members" },
"in": {
"k": "$$this.k",
"v": { "lastActive": "$$this.v.lastActive" }
}
}
}
}
}}
])