默认值不存在项目字段

Project field not exist by default value

我想将一个不存在的字段投影到默认值

集合A

{
  _id: ObjectId("6013859ba0c3120034d08bfa"),
  name: "A1",
  refs:[
   {id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
   {id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
  ]
}

集合B

{
  _id: ObjectId("6013859ba0c3120034d08bfb"),
  name: "B1",
  altName: "b1"
}

{
  _id: ObjectId("6013859ba0c3120034d08bfc"),
  name: "B2"
}

预期输出

{
    "_id" : ObjectId("6013859ba0c3120034d08bfa"),
    "name" : "A1",
    "refs" : [ 
        {
            "id" : ObjectId("6013859ba0c3120034d08bfb"),
            "text" : "ABC",
            "name" : "B1",
            "altName" : "b1"
        }, 
        {
            "id" : ObjectId("6013859ba0c3120034d08bfc"),
            "text" : "DEF",
            "name" : "B2",
            "altName" : "Unspecified"
        }
    ]
}

就我而言,我只想在项目表达式中执行此操作。 我试过 $project 就像

{
    $project: {
      ...,
        altName: {
          $first: { $ifNull: [ "$$refsB.altName", "Unspecified" ] }
        },
      }
    }
  }

您需要先通过$first 检索refsB.altName值,然后使用$ifNull检查并分配值(如果为空) .

altName: {
  $ifNull: [
    {
      $first: "$refsB.altName"
    },
    "Unspecified"
  ]
}

Complete query

db.collectionA.aggregate([
  {
    $unwind: "$refs"
  },
  {
    "$lookup": {
      "from": "collectionB",
      "localField": "refs.id",
      "foreignField": "_id",
      "as": "refsB"
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      refs: {
        id: "$refs.id",
        text: "$refs.text",
        name: {
          $first: "$refsB.name"
        },
        altName: {
          $ifNull: [
            {
              $first: "$refsB.altName"
            },
            "Unspecified"
          ]
        },
        
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      name: {
        $first: "$name"
      },
      refs: {
        $push: "$refs"
      }
    }
  }
])

Sample Mongo Playground