Query collection with array of values from another collection - MongoDB

Viewed 82

Let's say I want to make a sticker albums app, where users can "buy" albums and stickers, etc. So the relation between users and albums would be many-to-many. If my user collection looks like this

{"_id":{"$oid":"61a04f49909f8e972f5722f1"},"email":"1234@gmail.com","password":"$2b$10$g06lbwH4jNd4O9R/dbaqnus10iy1uhGeroge.bXkUeBxTSaVkR75a","albums_ids":["61a45889f3bedd5c1b7a9db4","61a45969f3bedd5c1b7a9db6"]}

with the albums_ids array referencing the objectIds of the "albums" collection

{"_id":{"$oid":"61a45889f3bedd5c1b7a9db4"},"name":"Brasil 2014"}

How can I create a query to get all the albums the user has in it's albums_ids array?

1 Answers

You will have to unwind the albums_ids first and do a lookup on the albums collection. After which do a unwind again and group them all up by user id and push/addToSet the albums into an array.

MongoDB Playground

db.users.aggregate([
  {
    $unwind: "$albums_ids"
  },
  {
    "$lookup": {
      "from": "albums",
      "localField": "albums_ids",
      "foreignField": "_id.oid",
      "as": "albums"
    }
  },
  {
    $unwind: "$albums"
  },
  {
    $group: {
      _id: "$_id.oid",
      albums: {
        "$push": "$albums"
      }
    }
  }
])

There might be a better query, my mongo is a bit rusty.

Related