I have the following documents in my MongoDB Aggregation stage:
_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
I want to create an Object field called players, and this object should contain the playerId
and a gender: 'male'
, but only if the document has a playerId property already. If not, it should just not do anything. So the result should look like this:
_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
I’ve tried to do this:
db.collection.aggregate([
{
$set: {
players: {
$cond: {
if: {
$ne: [
"$players",
undefined
]
},
then: {
$mergeObjects: [
"$players",
{
"gender": "male"
}
]
},
else: "$$REMOVE"
}
}
}
}
])
But this adds an object even if there is no playerId property in the document.
2
Answers
Works with
$cond
operator.If the
playerId
field is notundefined
, then set theplayers
field with an object.Else remove the
players
field with$$REMOVE
.Demo @ Mongo Playground
Demo at Mongo Playground