我在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字段,这个对象应该包含playerId
和gender: '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属性,这也会添加一个对象。
1条答案
按热度按时间20jt8wwn1#
使用
$cond
运算符。1.如果
playerId
字段不是undefined
,则使用对象设置players
字段。1.否则使用
$$REMOVE
删除players
字段。Demo @ Mongo Playground