A. L
A. L

Reputation: 12639

MongoDB - how to use $ifNull only on a field that exists

I'm using $lookup, which may or may not return something. But if it does, i need to check the looked up value and check a specific field to see if it is null, and if it is, set it to something.

I tried this:

{
    $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&"                                        
            ]
        }
    }
},

but it seems to have no effect on template.image.url (which is an array of objects), it actually returns an array instead, with one element as null.

Upvotes: 2

Views: 4821

Answers (2)

Ashh
Ashh

Reputation: 46441

You can use newer $lookup syntax to achieve the expected result

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"
  }}
])

Upvotes: 1

Sachin Shah
Sachin Shah

Reputation: 4533

Try with $project.

{
   $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&" 
       ]
      },
   }
} 

Upvotes: 0

Related Questions