Essay record

MongoDB: Check if Collection Exists

Record
Essay / / 1 min read / 159 words
Tags
Unfiled

DISCLOSURE: Some links may be affiliate links. Details

**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.

Built with CloudSeed Rust