Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda