如何将所有具有相同ID的文档分组到某个字段中,并计算其中一个字段中数组的长度。
就像下面的例子一样,结果应该是:
{
movieId: ("5b79b8387d467d5ab860544f")
takenSeats : 46
}
{
movieId : ("5b79b9277d467d5ab8605454")
takenSeats : 11
}
{
movieId : ("5b79b8927d467d5ab8605451")
takenSeats: 17
}
这是我开始聚合的方式:
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' }}}}
])
我通过此查询获得了所需的结果,但问题是,如果没有$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"}}},
])