我正在尝试构建一个汇总,在合并字段后,将返回其中一个字段中对象数量最多的文档。
假设有以下文件,其中两个在movie
字段内包含相同的ID
{
"_id" : ObjectId("5b79bb0c15d2d0697885467c"),
"movie" : [
ObjectId("5b79b8387d467d5ab860544f")
],
"takenSeats" : [{"id" : 1},{"id" : 2},{"id" : 4},
],
"creteDate" : ISODate("2018-08-14T18:46:36.090Z"),
}
{
"_id" : ObjectId("5b79bb0c15d2d069788ef48d"),
"movie" : [
ObjectId("5b79b8387d467d5ab860544f")
],
"takenSeats" : [{"id" : 2},{"id" : 7},{"id" : 4},
],
"creteDate" : ISODate("2018-08-14T18:46:36.090Z"),
}
{
"_id" : ObjectId("5b79bb0c15d2d069788fg54hq"),
"movie" : [
ObjectId("5b79b8387d467d5ab8df54h43")
],
"takenSeats" : [{"id" : 6},{"id" : 2},{"id" : 5},
],
"creteDate" : ISODate("2018-08-14T18:46:36.090Z"),
}
如您所见,两个文档在movie
字段中包含相同的ID。
我想做的是:提取movie
字段中包含相同ID的那些文档,并合并takenSeats
字段
想要的结果应该像
{
"_id" : ObjectId("5b79b8387d467d5ab860544f"),
"takenSeats" : [{"id" : 2},{"id" : 7},{"id" : 4},{"id" : 1},{"id" : 2},
{"id" : 4}
],
"creteDate" : ISODate("2018-08-14T18:46:36.090Z"),
}
{
"_id" : ObjectId("5b79b8387d467d5ab8df54h43"),
"takenSeats" : [{"id" : 6},{"id" : 2},{"id" : 5},
],
"creteDate" : ISODate("2018-08-14T18:46:36.090Z"),
}
在过去的几个小时中,我尝试使用$push
和$addToSet
之类的不同运算符来实现它。这是我所做的查询,它与我想要的结果最接近,但是我在结果中收到的文档具有重复的ID
db.orders.aggregate([
{$match:{ "created":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*15)}}},
{ $lookup: { from: "shows", localField: "showId", foreignField: "_id", as: "acociatedShow" } },
{ "$project": { "acociatedShow": 1 } },
{ $unwind : "$acociatedShow" },
{ "$group": {"_id": { "movie": "$acociatedShow.movie"},
"takenSeats": { "$addToSet": "$acociatedShow.takenSeats"}}},
{ $unwind : "$takenSeats" },
{ $group : { _id : "$takenSeats", movieId : { $first: '$_id.movie' },len : { $sum : 1 } } },
{ $limit : 3 },
{ $lookup: { from: "movies", localField: "movieId", foreignField: "_id", as: "topMovie" } },
{ $unwind: "$topMovie" }, { $replaceRoot: { newRoot: "$topMovie" } }
])