计算MonogDb文档中数组字段内的对象数量

时间:2018-08-21 16:36:13

标签: mongodb

如何将所有具有相同ID的文档分组到某个字段中,并计算其中一个字段中数组的长度。

就像下面的例子一样,结果应该是:

{ 
    movieId: ("5b79b8387d467d5ab860544f")
    takenSeats : 46 
}

{ 
   movieId : ("5b79b9277d467d5ab8605454")
   takenSeats : 11

}

{
   movieId : ("5b79b8927d467d5ab8605451")
   takenSeats: 17
}

MongoDb

这是我开始聚合的方式:

db.orders.aggregate([
        { $match:{ "created":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*15)}}}, 
        { $lookup: { from: "shows", localField: "showId", foreignField: "_id", as: "acociatedShow" }},
        { $unwind: "$acociatedShow" }, { $replaceRoot: { newRoot: "$acociatedShow" } },
        { $group: {_id: '$_id' ,movieId: { $first: '$movie' },takenSeats: { $first: '$takenSeats' }}}, 
 ])

[编辑]

结果使用:

db.orders.aggregate([
        { $match:{ "created":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*15)}}}, 
        { $lookup: { from: "shows", localField: "showId", foreignField: "_id", as: "acociatedShow" }},
        { $unwind: "$acociatedShow" }, { $replaceRoot: { newRoot: "$acociatedShow" } },
          { $group: {_id: '$movie',takenSeats: { $sum: {$size:'$takenSeats' }}}}
 ])

enter image description here

我通过此查询获得了所需的结果,但问题是,如果没有$push运算符,我可以将其缩短吗?

db.orders.aggregate([
        { $match:{ "created":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*15)}}}, 
        { $lookup: { from: "shows", localField: "showId", foreignField: "_id", as: "acociatedShow" }},
        { $unwind: "$acociatedShow" }, { $replaceRoot: { newRoot: "$acociatedShow" } },
        { $group: {_id: '$_id' ,movieId: { $first: '$movie' },takenSeats: { $first: '$takenSeats' }}}, 
        { $unwind: "$takenSeats" },       
        { $group:{ _id: "$movieId","takenSeats":{"$push": "$takenSeats"}}},
 ])

enter image description here

0 个答案:

没有答案