代码之家  ›  专栏  ›  技术社区  ›  A. L

mongodb-如何仅在存在的字段上使用$ifnull

  •  2
  • A. L  · 技术社区  · 6 年前

    我在用 $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 .

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    你可以用新的 $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"
      }}
    ])
    
        2
  •  0
  •   Sachin Shah    6 年前

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