Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!