---
# System prepended metadata

title: Mongo hack

---

# Mongo hack

## Update with using value inside doc

```
db.entities.updateOne(
    { entityId: 1553 },
    [{
        $set: {
            entities: [{
                orgnizationId: '$entity.organizationId',
                entityId: '$entity.entityId'
            }]
        }
    }]
])
```

### Results
<table>
    <tr>
        <td>Before</td>
        <td>After</td>
    </tr>
    <tr>
        <td>
            <pre>
{
  entityId: 1553
  organizationId: 45
}
            </pre>
        </td>
        <td>
            <pre>
{
  entityId: 1553
  organizationId: 45
  entities: [{
    organizationId: 45
    entityId: 1553,
  }]
 }
            </pre>
        </td>
    </tr>
</table>

## Set in aggregation

```
db.rakeLiveChat_Users.aggregate([
    { $match: { rakeLiveChatUserId: 1553 } },
    {
        $lookup: {
            from: 'entities',
            localField: 'entityId',
            foreignField: 'entityId',
            as: 'entity'
        }
    },
    { $unwind: '$entity' },
    {
        $set: {
            entities: [{
                orgnizationId: '$entity.organizationId',
                entityId: '$entity.entityId'
            }]
        }
    }
])
```

### Results
<table>
    <tr>
        <td>Before</td>
        <td>After</td>
    </tr>
    <tr>
        <td>
            <pre>
{
  rakeLiveChatUserId: 1553,
  entityId: 45
}
            </pre>
        </td>
        <td>
            <pre>
{
  rakeLiveChatUserId: 1553,
  entityId: 45,
  entities: [{
    organizationId: 4
    entityId: 45,
  }]
 }
            </pre>
        </td>
    </tr>
</table>

## Update fields if it not exists

```
db.entities.updateOne(
    { entityId: 808280 },
    [{
        $set: {
            lastName: {
                $switch: {
                    branches: [{ 
                      case: { $eq: [{ $type: "$lastName" }, 'missing'] }, 
                      then: 'lastName-3' 
                    }],
                    default: '$lastName'
                }
            },
            firstName: {
                $switch: {
                    branches: [{
                      case: { $eq: [{ $type: "$firstName" }, 'missing'] }, 
                      then: 'firstName-4'
                    }],
                    default: '$firstName'
                }
            }
        }
    }]
)
```

### Results
<table>
    <tr>
        <td>Before</td>
        <td>After</td>
    </tr>
    <tr>
        <td>
            <pre>
{
  entityId: 808280
  firstName: 'firstName-1'
}
            </pre>
        </td>
        <td>
            <pre>
{
  entityId: 808280
  firstName: 'firstName-1',
  lastName: 'lastName-3'
 }
            </pre>
        </td>
    </tr>
</table>
