Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
Referencing and Inserting ObjectId's from one collection to another as an array

I have two collections. One to store all the user Details and another to store movies. I have a user_id field which has the objectId of the user who uploads it in the movie collection. Now I need to store all the movie ObjectId's as a array in the corresponding user collection. Like one to many relationship. say, I have some movie documents :

     [{
          'id' : '1',
          'title' : 'Pk',
          'user_id' : '25'
      },
     {
          'id' : '2',
          'title' : 'Master',
          'user_id' : '25'
     }]

In user collection, I want to store all the Movie_id's as a array to the corresponding user.

      { 
         'user_id' : '25',
         'user_name' : 'john',
          'Movie_ids' : ['1','2']
      }

How can I achieve this using mongodb and express.js?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Query

  • $lookup does what you want (see mongodb documentation is very good)
  • $map is used to keep only the ids in the array

Test code here

db.users.aggregate([
  {
    "$lookup": {
      "from": "movies",
      "localField": "user_id",
      "foreignField": "user_id",
      "as": "movies"
    }
  },
  {
    "$set": {
      "movies": {
        "$map": {
          "input": "$movies",
          "in": "$$this.id"
        }
      }
    }
  }
])
about 4 years ago · Juan Pablo Isaza Relatório

0

Ok, I'm not sure if this is entirely what you are looking for but you can use javascript function .filter on the movie object to get all the movies with user_id=25 and then map the id's of those movies to a new array like this:

let movies = [
  {
    "id": "1",
    "name": "pk",
    "user_id": "25"
},{
    "id": "2",
    "name": "Master",
    "user_id": "25"
}]
let user = {
  "id": "25",
  "name": "john"
}

let sortedMovies = movies.filter(movie => movie.user_id  === user.id).map(movie => movie.id);
user.movieIDs = sortedMovies;

A link to test the code: https://playcode.io/816962/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda