How to validate existence of collection/database?

Hello,
There are two points I noted:

  1. I performed insertMany() operation (with a typo in collection name) on “movies” collection instead of “movieDetails” and the query succeeded! …I kept looking for updates (until I refreshed the dbs in Compass)

  2. Then, I tried to switch over to a non-existing database (could have been due to a typo) and it again succeeded.

Now, I understand the fact that mongodb creates a new instance if it doesn’t exist and that’s the reason behind it but How do I validate or check a collection/database for its existence in a particular case? If I’m inserting in a collection/database that doesn’t exist it should return an error.

Thanks

Yes in mongodb you will not get any error if non existent db or collection choosen or typo in fields

Choosen a non existent collection example
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db
test
MongoDB Enterprise Cluster0-shard-0:PRIMARY> show collections
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.example.find()
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.example.find().count()
0
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.example.stats()
{
“ns” : “test.example”,
“ok” : 0,
“errmsg” : “Database [test] not found.”,
“operationTime” : Timestamp(1553694218, 1),
“$clusterTime” : {
“clusterTime” : Timestamp(1553694218, 1),
“signature” : {
“hash” : BinData(0,“CZ0Ch/xwfcuDdN5p2kn2ADPTzCs=”),
“keyId” : NumberLong(“6627672121604571137”)
}
}
}

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.getCollectionNames().indexOf(“example”) >=0
false

2 Likes

Hi @Ramachandra_37567,
It means there has to be a manual process as a workaround, an overhead. Thanks for guiding.

Hi @Rishi_Kamal_23638,

I would like to add few more things to the @Ramachandra_37567’s reply.

You could also check for a Database or Collection using following list methods :

If you have any further doubts, please let me know.

Thanks,
Sonali

1 Like

Thanks @Sonali_Mamgain
I appreciate your help.