Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoDB-如何仅在存在的字段上使用$ifNull_Javascript_Mongodb - Fatal编程技术网

Javascript MongoDB-如何仅在存在的字段上使用$ifNull

Javascript MongoDB-如何仅在存在的字段上使用$ifNull,javascript,mongodb,Javascript,Mongodb,我正在使用$lookup,它可能返回或不返回某些内容。但是如果它是空的,我需要检查查找的值并检查一个特定的字段以查看它是否为空,如果为空,则将其设置为某个值 我试过这个: { $lookup: { from: "item_templates", localField: "based_on", foreignField: "_id", as:

我正在使用
$lookup
,它可能返回或不返回某些内容。但是如果它是空的,我需要检查查找的值并检查一个特定的字段以查看它是否为空,如果为空,则将其设置为某个值

我试过这个:

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

但它似乎对
template.image.url
(这是一个对象数组)没有影响,它实际上返回一个数组,其中一个元素为
null

请尝试使用
$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&" 
       ]
      },
   }
} 

您可以使用更新的
$lookup
语法来实现预期的结果

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

仍然将其转换为一个数组,其中一个元素为
null
。此外,该项目还去掉了所有其他字段,这是不可取的。在$project之前,也要展开
模板
。答案一如既往。