我正在寻找创建一个新的集合,为此从现有集合中获取计算数据
示例数据
{MID:100,stage:6,
hustle:[{id:1,name:"jack",level:4,target:10,completedTime:new Date("2015-12-12")},
{id:1,name:"jack",level:4,target:10,completedTime:new Date("2015-12-12")},
{id:1,name:"jack",level:4,target:10,completedTime:new Date("2015-12-12")},
{id:1,name:"jack",level:4,target:10,completedTime:new Date("2015-12-12")},
{id:82,name:"Mario",level:2,target:8,completedTime:new Date("2015-12-15")},
{id:82,name:"Mario",level:2,target:8,completedTime:new Date("2015-12-15")},
{id:82,name:"Mario",level:2,target:8,completedTime:new Date("2015-12-15")},
{id:82,name:"Mario",level:2,target:8,completedTime:new Date("2015-12-15")}]}
创建新集合" Recent_MID"有这个数据
{
"_id": 82,
"name": "Mario",
"level": 2,
"recentTIme": ISODate("2015-12-15T00:00:00Z"),
"accessCount": 4
} {
"_id": 1,
"name": "jack",
"level": 4,
"recentTIme": ISODate("2015-12-12T00:00:00Z"),
"accessCount": 4
}
答案 0 :(得分:1)
使用$out 运算符创建新集合,同时使用聚合
db.mid.aggregate([{
$unwind: "$hustle"
}, {
$group: {
_id: "$hustle.id",
name: {
$first: "$hustle.name"
},
level: {
$first: "$hustle.level"
},
recentTIme: {
$first: "$hustle.completedTime"
},
accessCount: {
$sum: 1
}
}
}, {
$out: "Recent_MID"
}]).pretty()