mongodb 如何仅在特定字段存在时投影对象?

nc1teljy  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(152)

我在MongoDB Aggregation阶段有以下文档:

_id: ObjectId('641316fd596514e63a2121ca'),
teamId: 5,
playerId: ObjectId('64131139596514e63a2121c1')
_id: ObjectId('641316fd596514e63a2121ca'),
teamId: 5,
playerId: ObjectId('64143f7702ede13fea5ff3be')
_id: ObjectId('64143f458b6a6cf54652d3a5'),
teamId: 17,
playerId: ObjectId('64143fa75a97b9a63a260e16')
_id: ObjectId('64143f4f9ba5f2b3cf3030e6'),
teamId: 3

我想创建一个名为players的Object字段,这个对象应该包含playerIdgender: 'male',但前提是文档已经有了playerId属性。如果没有,它应该什么都不做。所以结果应该是这样的:

_id: ObjectId('641316fd596514e63a2121ca'),
teamId: 5,
players: {
    gender: 'male',
    playerId: ObjectId('64131139596514e63a2121c1')
}
_id: ObjectId('641316fd596514e63a2121ca'),
teamId: 5,
players: {
    gender: 'male',
    playerId: ObjectId('64143f7702ede13fea5ff3be')
}
_id: ObjectId('64143f458b6a6cf54652d3a5'),
teamId: 17,
players: {
    gender: 'male',
    playerId: ObjectId('64143fa75a97b9a63a260e16')
}
_id: ObjectId('64143f4f9ba5f2b3cf3030e6'),
teamId: 3

我试着这样做:

db.collection.aggregate([
  {
    $set: {
      players: {
        $cond: {
          if: {
            $ne: [
              "$players",
              undefined
            ]
          },
          then: {
            $mergeObjects: [
              "$players",
              {
                "gender": "male"
              }
            ]
          },
          else: "$$REMOVE"
        }
      }
    }
  }
])

但即使文档中没有playerId属性,这也会添加一个对象。

20jt8wwn

20jt8wwn1#

使用$cond运算符。
1.如果playerId字段不是undefined,则使用对象设置players字段。
1.否则使用$$REMOVE删除players字段。

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      teamId: 1,
      players: {
        $cond: {
          if: {
            $ne: [
              "$playerId",
              undefined
            ]
          },
          then: {
            "gender": "male",
            "playerId": "$playerId"
          },
          else: "$$REMOVE"
        }
      }
    }
  }
])

Demo @ Mongo Playground

相关问题