Reputation: 69
I have this mongodb document :
{
"_id" : ObjectId("5e382d27bb4bd5ce3ef5fb1d"),
"code" : "25116",
"datecrea" : "2015-11-14 18:23:24",
"datemodif" : "2015-11-14 18:23:24",
"datas" : {
"songId" : 25116,
"artistId" : 128,
"albumId" : 1822,
"name" : "Free Me",
"songTrack" : 10,
"genres" : [
"24"
],
}
}
I want to make a request that search for the song by its genre which is an array
of genres, and then get me the artist
and the album
related to this song based on the datas.artistId
and datas.albumId
fields.
I have tried this query :
db.getCollection('songs').aggregate([
{ $elemMatch: { "datas.genre": 31 } },
{ $lookup: { from: "artists", localField: "datas.artisId", foreignField: "code", as: "artist" } },
{ $unwind: "$artist"}
])
But it returns an error, knowing that I totally news to mongodb. Thanks to everyone for helping
Upvotes: 1
Views: 38
Reputation: 22316
You are not far off. You just have two minor syntax errors.
The $elemMatch, Without going too much into it. $elemMatch
is not a pipeline stage and cannot be used in an aggregate
operation. it is typically used in a find query.
In the lookup you wrote datas.artisId
instead of datas.artistId
So change you're pipeline into this:
db.getCollection('songs').aggregate([
{ $match: { "datas.genre": 31 } },
{ $lookup: { from: "artists", localField: "datas.artistId", foreignField: "code", as: "artist" } },
{ $unwind: "$artist"}
])
One more fun fact, unrelated to the actual code, the word data
is already in it's plural form. hence datas
is a grammatical mistake. And in case you're wondering the singular form of data
is datum
.
Upvotes: 1