MongoDB: Check if Collection Exists

Date: 2016-05-30 |

**Problem: **I have a mongoDB setup on my machine. In my code, I’m branching off whether a collection exists or not. However, I can’t seem to find an easy way to check if a mongo collection exists in a given database. How can I check this?

**Solution: **The simplest solution I’ve found is to simply check the contents of the collection. If it holds no contents, then we act as if it doesn’t exist – it doesn’t hold anything, so it makes sense for us to make this distinction.

In most cases, mongo works well with this mindset, rarely – in my experience – throwing errors for accessing collections that don’t have any data. Rather, it just returns null when you access them.

So, to check if a collection exists, simply run:

db.collection.count()

If you get zero, treat it as if it doesn’t exist. If you get something else, then you know it contains something and must exist.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.