MongoDB "too many files open" even after setting limits

Since Ubuntu 16.04 uses systemd, you have to adapt the ulimit settings on a per service basis. To do so, create a file /etc/systemd/system/mongodb.service.d/override.conf and override the defaults.

root@xenial:~# sudo systemctl edit mongodb.service

Paste them:

[Service]
LimitNOFILE=infinity
LimitNPROC=infinity

Ctrl + O then Ctrl + X to exit and file /etc/systemd/system/mongodb.service.d/override.conf is created

root@xenial:~# cat /etc/systemd/system/mongodb.service.d/override.conf
[Service]
LimitNOFILE=infinity
LimitNPROC=infinity

To check if these settings were applied, you can use systemctl show. First, let's see the values that are active.

root@xenial:~# systemctl --no-pager show mongodb.service | egrep 'NOFILE|NPROC'
LimitNOFILE=1024
LimitNOFILESoft=1024
LimitNPROC=7839
LimitNPROCSoft=7839

Then apply the settings.

root@xenial:~# systemctl daemon-reload 
root@xenial:~# systemctl --no-pager show mongodb.service | egrep 'NOFILE|NPROC'
LimitNOFILE=18446744073709551615
LimitNOFILESoft=18446744073709551615
LimitNPROC=18446744073709551615
LimitNPROCSoft=18446744073709551615