On Sunday, 25 October 2015 06:20:33 UTC+11, Joe San wrote:
I’m pretty new to using MongoDB and I would like to create a startup script that would to the following:
- Take the location of my data and use a certain database
- check if a user and role exists, if not create them
- Check if a collection exists, if yes do nothing, if not create that collection
- Apply indexes on that collection
Could anyone please point me to some resources where I could get some help?
Hi Joe,
We’ll need some more details to point you in the right direction:
How do you envision running the startup script? Is this something that you would like to implement in a specific programming language, or via the mongo shell?
What specific version of MongoDB and O/S are you running?
Is this for a standalone, replica set, or sharded cluster deployment?
Take the location of my data and use a certain database
Can you clarify what you mean by location (i.e. looking for data in a certain path or as a parameter)?
check if a user and role exists, if not create them
All client drivers support this, but you should make sure that the driver you are using has full support for your version of MongoDB server (see: Driver Compatibility). If you are using the mongo shell, it should ideally match your version of MongoDB server.
Before managing users and roles, you should follow the general tutorial to Enable Client Access Control, if you haven’t already.
You will need to create an appropriate user with roles and required privileges for your startup script (e.g. userAdmin role).
Check if a collection exists, if yes do nothing, if not create that collection
There is no need to explicitly create a collection, but it can be useful to do so if specific options are required (capped collection, non-default compression setting for WiredTiger, etc). If you don’t have any non-default options to set, you can skip this step.
Apply indexes on that collection
If you create indexes (or insert data) for a collection that does not exist, that action will also create the collection namespace. Also, if you try to create an index that already exists the existing index will be unaffected.
Regards,
Stephen