我有以下MongoDB结构:
部门集合:
{ "_id": ObjectId("5b28cab902f28e18b863bd36"), "name": "Premier League", "teams": [ ObjectId("5b28cab902f28e18b863bd01"), ObjectId("5b28cab902f28e18b863bd02"), ObjectId("5b28cab902f28e18b863bd03"), ...
团队集合:
{ "_id": ObjectId("5b28cab902f28e18b863bd01"), "name": "Liverpool", "players": [ ObjectId('5b23tmb902f28e18b863bd01'), ObjectId('5b23tmb902f28e18b863bd02'), ObjectId('5b23tmb902f28e18b863bd03'), ...
播放机收藏:
{ "_id": ObjectId("5b2b9a8bbda339352cc39ec1"), "name": "Mohamed Salah", "nationality": [ ObjectId("5b23cn1902f28e18b863bd01"), ObjectId("5b23cn2902f28e18b863bd02"), ...
Countries 藏品:
{ "_id": ObjectId("5b23cn1902f28e18b863bd01"), "name": "England", "_id": ObjectId("5b23cn2902f28e18b863bd02"), "name": "Egypt", ...
如何使用MongoDB聚合( $lookup 、 $pipeline 等)获得结果,如下所示:
$lookup
$pipeline
{ "divisions": [ "_id": ObjectId("5b28cab902f28e18b863bd36"), "name": "Premier League", "teams": [ "_id": ObjectId("5b28cab902f28e18b863bd01"), "name": "Liverpool", "players": [ "_id": ObjectId("5b23tmb902f28e18b863bd01"), "name": "Mohamed Salah", "nationality": [ "_id": ObjectId("5b23cn2902f28e18b863bd02"), "name": "Egypt", "_id": ObjectId("5b23cn1902f28e18b863bd01"), "name": "England", "_id": ObjectId("5b28cab902f28e18b863bd37"), "name": "Championship", }
我设法进行了一级合并:
db.divisions.aggregate([ $lookup: { from: 'teams', localField: 'teams', foreignField: '_id', as: 'teams' ])
然后我遇到了困难,所以如果有人能帮我解决这个问题,我将非常感激。
【玩转 GPU】有奖征文
精美礼品等你拿!
您需要多层嵌套 $lookup 和 pipeline 。
pipeline
db.division.aggregate([ $lookup: { from: "teams", let: { teams: "$teams" pipeline: [ $match: { $expr: { $in: [ "$_id", "$$teams" $lookup: { from: "players", let: { players: "$players" pipeline: [ $match: { $expr: { $in: [ "$_id", "$$players" $lookup: { from: "countries", localField: "nationality", foreignField: "_id", as: "nationality" as: "players" as: "teams" ])
蒙戈游乐场样本
也许有人会有用。还可以使用populate方法合并数据:
db.divisions.find(_id: division_id).populate( path: 'teams', populate: { path: 'players',