Reputation: 109
I've got a mongo document as follows:
collection is leagues:
leagues { id = 1,
seasons {[
{ id: 2008,
teams: [
{ id: "abcdefghijklmnop1", name: "name01", roster: [{ ... }] },
{ id: "abcdefghijklmnopq", name: "name02", roster: [{ ... }] },
{ id: "abcdefghijklmnop3", name: "name03", roster: [{ ... }] },
]
},
{ id: 2009,
teams: [
{ id: "abcdefghijklmnop4", name: "name06", roster: [{ ... }] },
{ id: "abcdefghijklmnop5", name: "name09", roster: [{ ... }] },
{ id: "abcdefghijklmnop6", name: "name12", roster: [{ ... }] },
]
}
]
},
{ id = 2, ... }
A league has unique seasons. Each unique season has a unique list of "teams". Each team has a unique roster for that team for that season for that league.
This works great as a document and makes displaying of a league really easy, but is really hard to query to only return a given team for a given season for a given league.
Using:
db.leagues.find(
{"seasons.teams.id":"abcdefghijklmnopq"},
{"seasons": { $elemMatch : { "teams.id" : "abcdefghijklmnopq" }}}
);
works great for returning only a single season of a given league. But, all the teams for that season are still returned as part of the document.
Any suggestions on how to further limit the document result to only return the specific team?
Edit:
Also did this:
db.leagues.aggregate([
{$unwind: '$seasons'},
{$match: {'seasons.teams.id': 'abcdefghijklmnopq'}},
{$project: {_id: 0, id: '$seasons.teams.id'}}
]);
Which returns:
{ "id": ["id1...", "id2...", ... "idn..."] }
Upvotes: 1
Views: 44
Reputation: 19700
Assuming your teams document has an id field as your aggregation/find operations suggest, such as:
{ name: "name01",id:abc, roster: [{ ... }] }
You need to unwind
the seasons.teams
array too.
db.leagues.aggregate([
{$unwind:"$seasons"},
{$match:{"seasons.teams.id":"abcdefghijklmnopq"}},
{$unwind:"$seasons.teams"},
{$match:{"seasons.teams.id":"abcdefghijklmnopq"}},
{$group:{"_id":"$_id","id":{$push:"$seasons.teams.id"}}},
{$project:{"_id":0,id:1}}
])
Upvotes: 1