коллекция запросов A с отфильтрованными элементами из коллекции B - PullRequest
0 голосов
/ 08 февраля 2019

с учетом следующих двух коллекций песен и play_log

мне нужен один запрос агрегации монго с поиском, чтобы сделать магию, чтобы получить журнал воспроизведения всех песен, принадлежащих альбому Боуи "Scary Monsters", с соответствующей песнейinfo.

коллекция песен

[
    {artist: 'David Bowie', title: 'Ashes to Ashes', album: 'Scary Monsters', year:'1980', track_number: 4 ,label: 'RCA Records'},
    {artist: 'David Bowie', title: 'Fashion', album: 'Scary Monsters', year:'1980', track_number: 5 ,label: 'RCA Records'},
    ....
    {artist: 'U2', title: 'Sunday Bloody Sunday', album: 'war', year '1983', track_number: 1, label: 'Island Records'},
    {artist: 'U2', title: 'New Year's Day', album: 'war', year '1983', track_number: 3, label: 'Island Records'},
    {artist: 'U2', title: 'The Refugee', album: 'war', year '1983', track_number: 6, label: 'Island Records'},
    ....
]

коллекция play_log

[
    { created: '2019-02-08T11:05:33', station: 'BBC Radio 6', artist: 'David Bowie', title: 'Ashes to Ashes' },
    { created: '2019-01-17T01:33:57', station: 'BBC Radio 1', artist: 'U2', title: 'Sunday Bloody Sunday' },
    { created: '2018-09-08T12:21:32', station: 'BBC Radio 2', artist: 'Morrissey', title: 'Every day is like Sunday' },
    { created: '2019-02-08T11:11:11', station: 'BBC Radio 4', artist: 'David Bowie', title: 'Fashion' },
    ...
]

ожидаемый результат

[
    { created: '2019-02-08T11:05:33', station: 'BBC Radio 6', artist: 'David Bowie', title: 'Ashes to Ashes', album:'Scary Monsters', year:'1980', track_number: 4 ,label: 'RCA Records'},
    { created: '2019-02-08T11:11:11', station: 'BBC Radio 4', artist: 'David Bowie', title: 'Fashion', album: 'Scary Monsters', year:'1980', track_number: 5 ,label: 'RCA Records'},
    ...
]

1 Ответ

0 голосов
/ 10 февраля 2019

Это можно сделать с помощью агрегации, используя оператор $lookup, как показано ниже:

db.play_log.aggregate([
// Join using artist fields
   {
     $lookup:
       {
         from: "songs",
         localField: "artist",
         foreignField: "artist",
         as: "play_songs_logs"
       }
  },
  // Filter any empty array found in newly created collection: play_songs_logs
  {
      $match: { "play_songs_logs": { $ne: [] } }
   }, 
   // Match only required album, this can be done before filter also if make aggregate on songs collection
  {
  $match: 
      {
          "play_songs_logs.album" : "Scary Monsters"
      }
  },
  // Push all elements or merged the elements
  {
      $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$play_songs_logs", 0 ] }, "$$ROOT" ] } }
   },
   // Filter not required fields
   { $project: { play_songs_logs: 0, _id:0 } }
])

Вывод вышеуказанного запроса:

{ "artist" : "David Bowie", "title" : "Ashes to Ashes", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records", "created" : "2019-02-08T11:05:33", "station" : "BBC Radio 6" }
{ "artist" : "David Bowie", "title" : "Fashion", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records", "created" : "2019-02-08T11:11:11", "station" : "BBC Radio 4" }

Перед выполнением вышеуказанного запроса я вставилпредоставленные данные и запрос поиска

> db.play_log.find()
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4731"), "created" : "2019-02-08T11:05:33", "station" : "BBC Radio 6", "artist" : "David Bowie", "title" : "Ashes to Ashes" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4732"), "created" : "2019-01-17T01:33:57", "station" : "BBC Radio 1", "artist" : "U2", "title" : "Sunday Bloody Sunday" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4733"), "created" : "2018-09-08T12:21:32", "station" : "BBC Radio 2", "artist" : "Morrissey", "title" : "Every day is like Sunday" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4734"), "created" : "2019-02-08T11:11:11", "station" : "BBC Radio 4", "artist" : "David Bowie", "title" : "Fashion" }
>

> db.songs.find()
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4735"), "artist" : "David Bowie", "title" : "Ashes to Ashes", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4736"), "artist" : "David Bowie", "title" : "Fashion", "album" : "Scary Monsters", "year" : "1980", "track_number" : 5, "label" : "RCA Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4737"), "artist" : "U2", "title" : "Sunday Bloody Sunday", "album" : "war", "year" : "1983", "track_number" : 1, "label" : "Island Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4738"), "artist" : "U2", "title" : "New Year's Day", "album" : "war", "year" : "1983", "track_number" : 3, "label" : "Island Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4739"), "artist" : "U2", "title" : "The Refugee", "album" : "war", "year" : "1983", "track_number" : 6, "label" : "Island Records" }
>

Для получения подробной информации вы можете обратиться к официальным документам здесь: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

...