如何使用现有集合中的计算数据创建新集合 mongodb

How to create new collection, using computed data from existing collection mongodb

您好,我想创建一个新集合,以便从现有集合中获取计算数据,

示例数据

{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
}

使用$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()