Creating OneToMany references between existing MongoDB documents is a straightforward process that involves updating the relevant fields in

My first encounter with MongoDB has left me puzzled about creating references between documents that are already in the database. Unlike SQL, I am unsure how to establish relationships between collections.

I have two collections: Films and Actors. The Films collection contains information about different movies, like titles, unique URLs, descriptions, etc. Here is an example document from the Films collection:

{
  "_id": {
    "$oid": "6272aa886441c51b18de7b23"
  },
  "type": "Film",
  "title": "Les 2 papas et la maman",
  "genres": "Comedia",
  "description": "Jérôme and Delphine want a child but Jerome is sterile. They then ask the best friend of Jerome, Salim, to be the donor for artificial insemination of the mother...",
  "platform": "Netflix"
  "film_url": "exampleurl.com"
}

The second collection is called "Actors", each document containing details about a specific actor, the movie they star in (with title and URL), and the character they play. A sample document from the Actors collection could look like this:

{
  "_id": {
    "$oid": "6272ac5b6441c51b18de9ee4"
  },
  "name": "Sophie Rundle",
  "film_title": "Peaky Blinders",
  "film_url": "exampleurl.com",
  "character": "Ada Shelby",
  "num_episodes": "36"
}

I aim to create a OneToMany reference linking Films and Actors. This means a film can have multiple actors and each actor can represent a character in a film. To achieve this, I plan on adding an array within each Film document, containing the IDs of participating actors. Although I have unique "film_url" fields in both collections and data stored in CSV files, manually reading and iterating through over 10,000 lines in each file doesn't seem very efficient.

Is there a more straightforward and efficient method to establish these references in MongoDB?

Answer №1

If you're looking for a way to enhance and fill an array called "actorIds" in the Films collection, here's one approach to consider. Keep in mind that if your collections are substantial in size, this process may take some time as each film will need to fetch its respective actors. Utilizing indexes could potentially help optimize this process.

Prior to implementing this method, it is advisable to review MongoDB's cautionary note regarding "output to the same collection that is being aggregated". While unlikely, infinite loops can be troublesome, though I don't foresee them being an issue with this specific pipeline. Remember, the decision to proceed with this implementation rests solely on you - exercise caution and conduct thorough analysis before proceeding. External expert insights or opinions are also valuable in this scenario.

db.Films.aggregate([
  {
    "$lookup": {
      "from": "Actors",
      "localField": "film_url",
      "foreignField": "film_url",
      "pipeline": [
        {
          "$project": {
            "_id": 1
          }
        }
      ],
      "as": "actorIds"
    }
  },
  {
    "$set": {
      "actorIds": {
        "$map": {
          "input": "$actorIds",
          "in": "$$this._id"
        }
      }
    }
  },
  {
    "$merge": "Films"
  }
])

You can test this functionality on mongoplayground.net.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the lack of response from the jquery element on an

Recently, I've been working on a jQuery project with sticky headers. However, when I tested it on my iPad, I noticed a slight delay and the header jumping around the page. I'm wondering if this issue can be resolved within the code itself or if ...

Tips for managing serverside validation and clientside validation in your web application

Utilizing both clientside and serverside validation in ASP.NET controls is crucial for ensuring usability and security. While simple validations like length checks or regular expressions are easy to implement and maintain, more complex validations can beco ...

Implementing batchsize in Java for MongoDB find queries

When executing a find query in MongoDB using Java on a collection with a batchsize set to 500, I am only able to retrieve records 1-500 out of the total 10,000 records in my collection. How can I access the next set of records? Here is the code snippet: ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

Tips for setting a threshold in a highcharts ng chart

I am struggling with setting the threshold to zero on a simple line chart using Highchart ng. According to the Highcharts API, the property should be plotOptions.series.threshold. However, despite following advice from this source, I can't seem to get ...

What causes the exception in JavaScript to be an empty object?

try { let temporary = null; temporary.split(','); } catch (error) { Logger().info('caught error: ', error, error.constructor); } output: caught error: {} undefined I attempted to use JSON.stringify and encountered the sa ...

Using an AJAX post request will result in receiving an HTML element, especially when an attachment is included with Paperclip

I've created an innovative application where users can share their stories through ajax submissions and engage with other readers by commenting on the stories using ajax as well. The technology stack I'm working with includes Rails 3.0.3, ruby 1. ...

PHP + MySQL + JavaScript for an Interactive Web Communication Platform

My goal is to develop a Web Chat system using PHP, MySQL, and JavaScript. Currently, I store messages in a MySQL database with an incremental ID (indexed), timestamp, sender, and message. To retrieve new messages, I use AJAX to query the database every 50 ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

The website no longer uses AJAX calls and does not display any errors, although it used to do so in the past

I've noticed that my website is no longer making the ajax call it used to make before I made some changes to my code. However, I can't seem to figure out what exactly I changed. The function call appears to be correct as it triggers the initial a ...

Expanding Text Area in AngularJS

I came across this directive and I want to integrate it into my project, but I need the text area to expand as soon as the content is loaded. Angular-Autogrow.js: (function(){ 'use strict'; angular.module('angular-autogrow', [ ...

Utilizing one JavaScript file and consistent classes for multiple modals

Is it possible to have multiple modals using the same JS file, classes, and IDs? I created this code: <button id='myBtn'>Order/Discount</button> <div id='myModal' class='modal'> <div clas ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

Troubleshooting issues with reinitializing Select2

I am facing an issue with my selectboxes, where one depends on the other. To update the options in the dependent selectbox, I have implemented AJAX functionality. Additionally, both selectboxes utilize the select2 plugin as shown below: $(document).ready( ...

What could be causing my JQuery code to fail after loading data via ajax?

My tree view is set up using the following jQuery code: $(".treeView").on("click", ".CollOpen, .CollClosed", function () { $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle(); }); Initially, this code works perfectly. ...

Disabling the Autocomplete Drop-Down Arrow

Can the drop-down arrow icon be removed from the material-ui Autocomplete react component? My current view includes a blue arrow that I'd like to remove, opting instead for text to automatically drop down as I type. https://i.stack.imgur.com/ZTLYu.p ...

When the specified width is reached, jQuery will reveal hidden circular text upon page load instead of keeping it hidden

My current issue involves utilizing jQuery to hide circular text when the window width is below 760px. Although the functionality works as intended, there is a minor problem when the page loads under 760px width - the text briefly shows up before hiding ag ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Read special characters such as ä, ö from standard input using Node.js

I attempted to read input from the console in node.js using the code snippet below process.stdin.setEncoding("utf8"); process.stdout.setEncoding("utf8"); process.stdin.on('data', function(data) { process.stdout.write('data: ' + dat ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...