Utilizing $ifNull in MongoDB specifically for existing fields

When utilizing the $lookup function, there is a possibility of it returning a value. In such cases, one must check the looked up value and see if a specific field is null; if it is, then it needs to be assigned a certain value.

An attempt was made with the following code:

{
    $lookup:
    {
        from: 
            "item_templates",
        localField:
            "based_on",
        foreignField:
            "_id",
        as:
            "template"
    }
},
{
    $addFields:
    {
        "template.image.url":
        {
            $ifNull:
            [
                "$template.image.url",
                "http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"                                        
            ]
        }
    }
},

However, the above code does not seem to have any impact on the template.image.url (which is an array of objects), instead returning an array with only one element set as null.

Answer №1

To achieve the desired outcome, you have the option to utilize the latest $lookup syntax.

db.collection.aggregate([
  { "$lookup": {
    "from": "item_templates",
    "let": { "based_on": "$based_on" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$based_on"] }}},
      { "$addFields": {
        "image.url": {
          "$ifNull": [
            "$image.url",
            "http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&"
          ]
        }
      }}
    ],
    "as": "template"
  }}
])

Answer №2

Experiment with the $project command.

{
   $unwind:{
       path: "$template",
       includeArrayIndex: "arrayIndex",
       preserveNullAndEmptyArrays: true
   }
},
{
   $project:{
     template.image.url: { 
        $ifNull: [ 
             "$template.image.url", 
              "http://via.placeholder.com/400x700/d3d3d3/000000/?text=No%20Image&" 
       ]
      },
   }
} 

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 are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

Eliminate unnecessary repetition of code in JavaScript

Is it possible to avoid repeating the same code in JavaScript and instead write it once but still use it multiple times? I tried using a class, but it didn't work as expected. Here is the HTML: <img id="Image" src="1.jpg" alt="1" style="width:50% ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Arranging the properties of an object following the reduction process

I am currently working on replicating the functionality of an Outlook mailbox by organizing a list of Outlook emails based on their conversation ID. However, I am facing the challenge of needing to sort my list twice - once to order the emails in each grou ...

Retrieve a collection of Vue components

My single page website has a simple component structure: <template> <div id="app"> <header /> <section-about /> <section-warranty /> <section-advantages /> <section-service /> <section ...

Can you guide me on implementing an onclick function in a unique React Component?

As a newcomer to React, I find myself faced with a challenge. I have 3 buttons that are brought in as a Component into App.js using the following import statement: import Button from "./Button"; The task at hand is to add an onClick function to ...

What does the error message "unsupported command-line flag" in Chrome mean for Protractor?

Recently jumping on the Protractor bandwagon, I found myself facing an issue while running my tests on Chrome (an error message appears below the address bar in the browser): A worrisome warning popped up saying something about '--ignore-certificat ...

Exploring the Differences Between Meteor JS Backend and Express JS

I have a basic understanding, but I'm interested in learning more: I came across a comparison on Stack Overflow that likened Meteor JS and Express JS to oranges and potatoes. My current understanding is that Meteor JS is full stack (Front End, Back E ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

Find and compare certain data points within a single line

My goal is to extract specific values from a URL, focusing on the parameters and their respective values. Since a parameter can appear multiple times in the URL, I need to retrieve all instances along with their corresponding values. &myparameter[123 ...

Could you explain why my code is not functioning as intended when I attempt to modify the class of a specific element?

I've been trying to change the class of a specific <li></li> element, but none of the methods I've attempted seem to be working. Could you please help me figure out why my code isn't functioning as expected? <script type="tex ...

Adjust the height of siblings based on the height of the contenteditable element(s)

I'm currently struggling with a situation that I can't seem to figure out. Within a container (outer), I have three children. My goal is to resize the middle container (div) based on the height of the contenteditable area. All three containers s ...

Notification box appears only when closing the window, not when reloading the page

I've been trying to find a way to remind my users to log out before closing the window. I found this code that seems to work: window.onbeforeunload = confirmExit; function confirmExit() { return "It's best to log out before you close this pa ...

React does not allow functions as child elements. I have thoroughly reviewed my code and cannot identify the source of this issue

I have a parent component with a lot of logic and several other components that are functional components with only the return JSX method. I kept getting a lot of "Functions are not valid as a React child" errors, so I made some changes to fix this. I thou ...

Can PayPal sandbox accounts in Vue be used to process live transactions on a recently launched website?

I have completed the development of my app and now I am looking to host it online. Can I allow my clients to use sandbox accounts for real transactions? This is my first time creating an app with live online transactions using Paypal. Do I need to modify t ...

The HTML5 video tag is having trouble playing an .mp4 file that lacks an audio codec

I have been facing an issue while trying to upload a video to an Angular app using ng-file-upload. Everything works properly until I attempt to upload a .mp4 video without any audio codec. The video element appears, shows the correct duration in the contro ...

Navigating back to the beginning of the webpage following the completion of a form submission utilizing Master Pages and Ajax

I am having an issue with my ASP.NET 4.0 page where I want to reset it to the top after a form submission so that the validation summary can be displayed properly. The setup involves using Ajax and a master page with the following simplified code: <f ...

Guide on accessing a Sequelize model within an Express.JS application

Here is my user.js Sequelize class: 'use strict'; const {Sequelize} = require('sequelize'); const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { class User extends Model { /** * ...

What is the method of V8 in Google Chrome or Node.js for converting floating point numbers to strings?

When dealing with integer numbers, the method operates smoothly as shown below: (25).toString(2) = '11001' (25).toString(16) = '19' (25).toString(36) = 'p' However, using floats produces different results: (0.1).toString(2 ...

What is the best way to attach several URLs to a single component?

I am currently using Next.js Here is the structure I have: https://i.stack.imgur.com/jRQBS.png I am in need of opening the same component for multiple URLs, such as 'http://localhost:3000/hakkimizda', 'http://localhost:3000/cerez-politika ...