MongoDB Sensu Script(Check) not showing Metrics in Log - mongodb

I have sensu client installed on Mongo DB server and I am executing the Mongo DB Check using this script It Works great when my Mongodb is configured without Authentication, But it does not show the metrics when Authentication is enabled on the Mongo DB, Though I am passing the DB Authentication Credentials correctly, but authentication works with same credential from irb prompt. What should be the fix to get the Monitoring Metric using MongoDB Authentication ?
I am using Sensu version 0.1 6 and MongoDB 2.4.11 on Ubuntu 12.04.

I resolved it,
In fact it is not an sensu-plugin issue, it was an user authentication issue with MongoDB 2.4, Mongo allows the user which is created within admin db to collect the information of other databases.
So the following simple steps solved my issue
rahul#rahul:~$ mongo
MongoDB shell version: 2.4.12
connecting to: test
> use admin
switched to db admin
> db.addUser("rahul","rahul#123")
{
"user" : "rahul",
"readOnly" : false,
"pwd" : "85a20670734aeb830a7903183bd4132f",
"_id" : ObjectId("54d88f4950e99f42d01abfe8")
}
> use mydb
switched to db mydb
>
Then I modified following paramaters in mongodb-metrics.rb which is freely available here
option :user,
description: 'MongoDB user',
long: '--user rahul',
default: nil
option :password,
description: 'MongoDB password',
long: '--password rahul#123',
default: nil
and note that the following has to be unchanged
db_name = 'admin'
here I was giving db_name as 'mydb' which was going wrong
after all I can see my metrics and graphs

Related

not able to run "show dbs" on mongodb on Bitnami image instance from aws ec2 instance [duplicate]

I am trying to add authorization to my MongoDB.
I am doing all this on Linux with MongoDB 2.6.1.
My mongod.conf file is in the old compatibility format
(this is how it came with the installation).
1) I created admin user as described here in (3)
http://docs.mongodb.org/manual/tutorial/add-user-administrator/
2) I then edited mongod.conf by uncommenting this line
auth = true
3) Finally I rebooted the mongod service and I tried to login with:
/usr/bin/mongo localhost:27017/admin -u sa -p pwd
4) I can connect but it says this upon connect.
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:47:16 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
5) Now it seems this sa user I created has no permissions at all.
root#test02:~# mc
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:57:03 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
[admin] 2014-05-29 17:57:03.011 >>> use admin
switched to db admin
[admin] 2014-05-29 17:57:07.889 >>> show collections
2014-05-29T17:57:10.377-0400 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[admin] 2014-05-29 17:57:10.378 >>> use test
switched to db test
[test] 2014-05-29 17:57:13.466 >>> show collections
2014-05-29T17:57:15.930-0400 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[test] 2014-05-29 17:57:15.931 >>>
What is the problem? I repeated this whole procedure 3 times and
I think I did it all as specified in the MongoDB docs. But it doesn't work.
I was expecting this sa user to be authorized to do anything so that
he can then create other users and give them more specific permissions.
I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user.
use admin
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
exit;
If you have already created the admin user, you can change the role like this:
use admin;
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
For a complete authentication setting reference, see the steps I've compiled after hours of research over the internet.
It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite
Perhaps a quick example of how to change a current user will be helpful to somebody. This is what I was actually looking for.
Following advice of #JohnPetrone I added readWrite role to my admin user with grantRolesToUser
> use admin
> db.grantRolesToUser("admin",["readWrite"])
> show collections
system.users
system.version
You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
I know this answer is coming really late on in this thread but I hope you check it out.
The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root will solve your problem but you must first understand what these roles do exactly before granting them to users.
In tutorial you granted the user the userAdminAnyDatabase role which basically give the user the ability to manage users of all your databases.
What you were trying to do with your user was outside its role definition.
The root role has this role included in it definition as well as the readWriteAnyDatabase, dbAdminAnyDatabase and other roles making it a superuser (basically because you can do anything with it).
You can check out the role definitions to see which roles you will need to give you users to complete certain tasks.
https://docs.mongodb.com/manual/reference/built-in-roles/
Its not advisable to make all your users super ones :)
It's a simple question.
It's important that you must switch the target db NOT admin.
use yourDB
check your db authentication by
show users
If you get a {} empty object that is the question. You just need to type
db.createUser(
{
user: "yourUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
} )
or
db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :)
Try this:
Choose your project in the MongoDB atlas website
Connect/Connect with MongoDB Compass
Download Compass/Choose your OS
I used Compass 1.12 or later
Copy the connection string under the Compass 1.12 or later.
Open MongoDB Compass/Connect(top left)/Connect To
Connection String detected/Yes/
Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
Connect & Tested the API with POSTMAN.
Succeed.
Use the same connection string in your code too:
Before:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/admin
After:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/projectname
Good luck.
Use Admin :
use admin
Create a super user :
db.createUser(
{
user: "master",
pwd: "test#123",
roles: [
{
role: "readWriteAnyDatabase",
db: "admin"
},
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "clusterAdmin",
"db" : "admin"
},
"userAdminAnyDatabase"
]
}
)
If you're using Atlas, note that you can't create users through the mongo shell.
I was banging my head against the wall for a while till I came across this:
https://www.mongodb.com/community/forums/t/cant-create-a-root-user-from-mongo-shell/101369
I came across this thread with a similar issue, but my problem was that I used the collection name instead of the database name.
I had a similar problem here on a Windows environment: I have installed Bitnami DreamFactory and it also installs another MongoDb that is started on system boot. I was running my MongoDbService (that was started without any error) but I noticed after losing a lot of time that I was in fact connecting on Bitnami's MongoDb Service. Please, take a look if there is not another instance of mongoDB running on your server.
Good Luck!
In addition, notice that if your mongo shell client fails to connect correctly to the mongod instance, you can receive such "Permission Denied" errors.
Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod is not in use. You can set a different port by using the --port <port> parameter in both the shell and the process.
use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )
Agreed that you've to get authenticated to admin db and needs at least a role with correct privileges which would avoid 'local host exception' from DB(this is for mongoDB's hosted on-premises), though you've everything in place & still getting not authorized exceptions on almost every command, while accessing mongoDB which got created using Mongo Atlas, then here is the place where you might know the reason, why :
https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster?newreg=471a9a26108243d78d4ca74a87e7a115
and also check this if you've hosted mongoDB on mongo Atlas:
https://docs.atlas.mongodb.com/unsupported-commands/
I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T
For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is
mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want
This may be because you havent set noAuth=true in mongodb.conf
# Turn on/off security. Off is currently the default
noauth = true
#auth = true
After setting this restart the service using
service mongod restart

Cannot access mongoDB after "meteor deploy myapp.com"

I deployed my app using meteor deploy myapp.com, and directed my DNS to myapp.meteor.com.
The app is now available at myapp.com, and I have no problem running it. It's the correct version that was deployed to "myapp.com" and not the older "myapp.meteor.com" version.
But I cannot access mongodb for this deployed version.
When I run meteor mongo myapp.com, I get this at the terminal:
MongoDB shell version: 2.6.7
connecting to: sg-mother1-6242.servers.mongodirector.com:27017/myapp_com
2016-03-10T16:46:18.659-0800 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1210
exception: login failed
I am also getting the same error when I run meteor mongo myapp.meteor.com:
MongoDB shell version: 2.6.7
connecting to: someserver.servers.mongodirector.com:27017/myapp_meteor_com
2016-03-10T16:45:54.367-0800 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1210
exception: login failed
When I do meteor mongo --url myapp.com, I do get a URL back of the form:
mongodb://<user>:<password>#<some-servername>.servers.mongodirector.com:27017/myapp_com
But I cannot connect to this URL using Robomongo. I get an error:
Cannot connect to MongoDB (<some-servername>.servers.mongodirector.com:27017),
error: Unable to connect to MongoDB
What am I doing wrong? How do I connect to the mongoDB for the app I deployed on my custom domain? Preferably using some GUI tool such as Robomongo?
What I understand, is that the local install of Meteor uses Mongodb 2.6 and newly deployed Meteor sites use Mongodb 3.0
When you call meteor mongo myapp.meteor.com you are using meteor's locally installed version of mongo (version 2.6) but you are trying to access the deployed mongodb (version 3.0). This results in the authentication error you are getting.
This link describes a workaround that worked for me. I had to tweak it a little, but this is what I did:
Install or update your local version of Mongo (not through Meteor).
Run the command meteor mongo --url myapp.meteor.com to get the MONGO_URL. As you already mentioned, you'll get something like
mongodb://<user>:<password>#<some-servername>.servers.mongodirector.com:27017/myapp_com
Connect to the MONGO_URL using your updated non-meteor version of mongo by running
mongo mongodb://<user>:<password>#<some-servername>.servers.mongodirector.com:27017/myapp_com
You should now be in the mongoshell, connected to your deployed mongodb. You should see something like this RS-mother1-0:PRIMARY> in your mongo shell. You still need to switch to your app's DB though. So call use myapp_com from the shell.
You should now be able to view collections and run mongo commands on your deployed meteor mongodb.
I'm not sure why you can't connect to Robomongo using the username and password meteor generates for you in the MONGO_URL. I suspect it's because it might expire. If you still want to connect using Robomongo, I'd recommend creating a user on the database now that you are logged in. And then later on, using that user to log into Robomongo.
Creating the user in the mongo shell:
db.createUser({ "user" : "my_user", "pwd": "my_password", "roles" : ["readWrite"]})
New MONGO_URL:
mongodb://my_user:my_password#<some-servername>.servers.mongodirector.com:27017/myapp_com

MongoDB-CR Authentication failed

I am getting following error while authenticating user : purchase_user#purchase failed. MongoDB-CR Authentication failed. Missing credentials in user document when I access webservice through browser.
But I am able to authenticate purchase_user from mongo it returns 1 .
go to mongoDB console and delete your current user & set authSchema version to 3 instead of 5 , follow these commands in mongo console -
mongo
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
Now restart the mongod and create new user then it should work fine.
Note: use remove commands in test db only, if in production use update.
Authentication information for Kubernetes Helm Chart
If you delete the all users and authentication is enabled in the configuration (or --auth param which is set per default on the Kubernetes helm chart), it's not possible to access MongoDB any more. Its required to disable authentication, create a new user and then re-enable it.
On Kubernetes you need to edit the parameters and add --noauth as argument, since it's not the default there as on a classic installed MongoDB. Please see the CLI documentation for more information about --noauth and the corresponding --auth.
Had the same issue. What was happening to me was that when I use MongoDB 3 to create my user, it was using SCRAM-SHA-1 as it's authentication mechanism instead of MongoDB-CR. What I had to do was:
List item
Delete the created user.
Modify the collection admin.system.version such that the authSchema's currentVersion is 3 instead of 5 (3 is using MongoDB-CR).
Recreate your user.
Should work without problems now.
The step number 2. above is not detailed explicitly, I found this solution and worked for me.
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
I think this is the answer you need:
1) Start 3.0 without auth enabled. (Auth needs to be disabled otherwise you'll get the not authorized error).
2) Run (after selecting "admin"use db):
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
3) restart mongodb with auth enabled.
4) Create a new admin user (the old one, the one you created before this workaround won't work).
Things should work now. This issue was driving me crazy as well.
Answer came from here: https://jira.mongodb.org/browse/SERVER-17459
Adding to above solution by Vivek & explanation taken from here
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
you only need to downgrade the schema to create MONGODB-CR users.
Once they are there the old drivers will work regardless of the value
of authSchemaVersion. However if you run authSchemaUpgrade to change
from "3" to "5" the users will obviously be upgraded.
My comment regarding new users was that if you have existing SCRAM
users and change the schema manually to "3" the user documents won't
be consistent with the new schema. This is not enforced however but
the SCRAM users will still work for any driver supporting SCRAM.
Upgrade mongo-java-driver to 3.0.3 and use :-
MongoCredential.createScramSha1Credential instead of MongoCredential.createMongoCRCredential
MongoCredential createMongoCRCredential = MongoCredential.createScramSha1Credential(mongoConfiguration.getDatabaseUserName(), mongoConfiguration.getAuthenticationDatabase(),mongoConfiguration.getDatabasePassword().toCharArray());
http://docs.mongodb.org/master/release-notes/3.0-scram/
For me I was using a mongo 2 client trying to connect to a mongo 3 server. Upgrading the client fixed the issue.
I was getting this error as well.
Check your Spring Config file.. I had a constructor arg named "MONGODB-CR" which I swapped to "SCRAM-SHA-1" and it fixed my issue.
tailing the mongodb log file helped me diagnose this.
uninstall mongodb-clients packages provided by Ubuntu
install mongodb-org-shell provided by official MongoDB
This solved the problem, because The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB. You should always use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
Probably old news, and problem solved, but adding my experience with the same error:
I had the exact same problem (using MongoDB 3.0), and a C# driver that was setup to use a pre 3.0 db.
In C# I used "MongoDB.Driver.CreateMongoCRCredentials()", which caused the error the OP was getting.
The fix (for me), was to switch the command above to "MongoDB.Driver.CreateCredential()".
I guess this could be caused by using "old" users (from pre 3.0) on an upgraded system. Which either forces you to upgrade your users to the new authentication mechanism, or downgrade the authentication mechanism on your server.
June 2018 I got this error after trying to connect to my Mongodb version 3.6 from an ancient client installed in /usr/bin. I installed the mongo DB in a separate folder outside of the OS standard directory, and so my installation was conflicting with the ancient version installed by the package manager.
For those who is struggling to update auth schema (see the accepted answer) in MongoDB 3.6 due to the not authorized on admin to execute command and removing FeatureCompatibilityVersion document is not allowed errors, this is what's worked for me.
To resolve the first error:
> db.system.version.remove({})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on admin to execute command { update: \"system.version\", ordered: true, lsid: { id: UUID(\"58e86006-d889-440a-bd83-ad09fcd81747\") }, $db: \"admin\" }"
}
})
I had to create a custom role that permits any action on any resource and a user with this role, then login to the admin database with that new user:
mongo admin
db.createUser({user: 'admin', pwd: 'mypwd', roles: ['root']})
exit
mongo admin -u admin -p
db.createRole({role: 'fullaccess', privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}], roles: []})
db.createUser({user: 'superadmin', pwd: 'mypwd', roles: ['fullaccess']})
exit
mongo admin -u superadmin -p
(Just using the admin user with root role or disabling security.authorization in config didn't work for me and still had the same error when trying to update the system.version table.)
After that I had another error:
> db.system.version.remove({})
WriteResult({
"nRemoved" : 0,
"writeError" : {
"code" : 40670,
"errmsg" : "removing FeatureCompatibilityVersion document is not allowed"
}
})
To resolve it, we should only update the authSchema document instead of removing the whole collection.
(Generally speaking, you shouldn't blindly remove everything from system tables in production and always check what would be the implications of updating them, so that's another reason to update the needed record only.)
db.system.version.update({"_id": "authSchema"}, {currentVersion: 3})
Now you should be able to create a user with the old authentication mechanism. You also might need to switch to your database first, so that the user is created in that database rather than in admin one. Otherwise you'd have to use the authSource=admin parameter in your connection string.
(I'm actually lying here - it still will be created in admin database, just with mydb.myuser id instead of admin.myuser. But I use the same way of describing these things that's being used in MongoDB documentation. I suppose this is how it actually used to work in previous versions and in general we shouldn't care about the internal implementation details.)
use mydb
db.createUser({user: 'myuser', pwd: 'mypwd', roles: [{role: 'dbOwner', db: 'mydb'}]})
And don't forget to cleanup:
use admin
db.system.version.update({"_id": "authSchema"}, {currentVersion: 5})
exit
mongo admin -u admin -p
db.dropUser('superadmin')
db.dropRole('fullaccess')
You may want to keep the admin user - I was not able to create it again even with security.authorization setting disabled. It looks like if there are any records in admin.system.users table, the setting does not work anymore and mongo requires authentication to do something.
I had the same error with a Spring Boot app using a new MongoDB 3.2.8 database. By upgrading to the latest version of the Java Mongo driver (3.2.2) and then adding the authentication mechanism param to the URI in my application.properties, I was able to get it working:
spring.data.mongodb.uri=mongodb://myusername:mypassword#localhost/?authSource=admin&authMechanism=SCRAM-SHA-1
spring.data.mongodb.database=test

MongoDB - admin user not authorized

I am trying to add authorization to my MongoDB.
I am doing all this on Linux with MongoDB 2.6.1.
My mongod.conf file is in the old compatibility format
(this is how it came with the installation).
1) I created admin user as described here in (3)
http://docs.mongodb.org/manual/tutorial/add-user-administrator/
2) I then edited mongod.conf by uncommenting this line
auth = true
3) Finally I rebooted the mongod service and I tried to login with:
/usr/bin/mongo localhost:27017/admin -u sa -p pwd
4) I can connect but it says this upon connect.
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:47:16 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
5) Now it seems this sa user I created has no permissions at all.
root#test02:~# mc
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:57:03 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
[admin] 2014-05-29 17:57:03.011 >>> use admin
switched to db admin
[admin] 2014-05-29 17:57:07.889 >>> show collections
2014-05-29T17:57:10.377-0400 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[admin] 2014-05-29 17:57:10.378 >>> use test
switched to db test
[test] 2014-05-29 17:57:13.466 >>> show collections
2014-05-29T17:57:15.930-0400 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[test] 2014-05-29 17:57:15.931 >>>
What is the problem? I repeated this whole procedure 3 times and
I think I did it all as specified in the MongoDB docs. But it doesn't work.
I was expecting this sa user to be authorized to do anything so that
he can then create other users and give them more specific permissions.
I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user.
use admin
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
exit;
If you have already created the admin user, you can change the role like this:
use admin;
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
For a complete authentication setting reference, see the steps I've compiled after hours of research over the internet.
It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite
Perhaps a quick example of how to change a current user will be helpful to somebody. This is what I was actually looking for.
Following advice of #JohnPetrone I added readWrite role to my admin user with grantRolesToUser
> use admin
> db.grantRolesToUser("admin",["readWrite"])
> show collections
system.users
system.version
You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
I know this answer is coming really late on in this thread but I hope you check it out.
The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root will solve your problem but you must first understand what these roles do exactly before granting them to users.
In tutorial you granted the user the userAdminAnyDatabase role which basically give the user the ability to manage users of all your databases.
What you were trying to do with your user was outside its role definition.
The root role has this role included in it definition as well as the readWriteAnyDatabase, dbAdminAnyDatabase and other roles making it a superuser (basically because you can do anything with it).
You can check out the role definitions to see which roles you will need to give you users to complete certain tasks.
https://docs.mongodb.com/manual/reference/built-in-roles/
Its not advisable to make all your users super ones :)
It's a simple question.
It's important that you must switch the target db NOT admin.
use yourDB
check your db authentication by
show users
If you get a {} empty object that is the question. You just need to type
db.createUser(
{
user: "yourUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
} )
or
db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])
If you're using Atlas, note that you can't create users through the mongo shell.
I was banging my head against the wall for a while till I came across this:
https://www.mongodb.com/community/forums/t/cant-create-a-root-user-from-mongo-shell/101369
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :)
Try this:
Choose your project in the MongoDB atlas website
Connect/Connect with MongoDB Compass
Download Compass/Choose your OS
I used Compass 1.12 or later
Copy the connection string under the Compass 1.12 or later.
Open MongoDB Compass/Connect(top left)/Connect To
Connection String detected/Yes/
Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
Connect & Tested the API with POSTMAN.
Succeed.
Use the same connection string in your code too:
Before:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/admin
After:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/projectname
Good luck.
Use Admin :
use admin
Create a super user :
db.createUser(
{
user: "master",
pwd: "test#123",
roles: [
{
role: "readWriteAnyDatabase",
db: "admin"
},
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "clusterAdmin",
"db" : "admin"
},
"userAdminAnyDatabase"
]
}
)
I came across this thread with a similar issue, but my problem was that I used the collection name instead of the database name.
I had a similar problem here on a Windows environment: I have installed Bitnami DreamFactory and it also installs another MongoDb that is started on system boot. I was running my MongoDbService (that was started without any error) but I noticed after losing a lot of time that I was in fact connecting on Bitnami's MongoDb Service. Please, take a look if there is not another instance of mongoDB running on your server.
Good Luck!
In addition, notice that if your mongo shell client fails to connect correctly to the mongod instance, you can receive such "Permission Denied" errors.
Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod is not in use. You can set a different port by using the --port <port> parameter in both the shell and the process.
use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )
Agreed that you've to get authenticated to admin db and needs at least a role with correct privileges which would avoid 'local host exception' from DB(this is for mongoDB's hosted on-premises), though you've everything in place & still getting not authorized exceptions on almost every command, while accessing mongoDB which got created using Mongo Atlas, then here is the place where you might know the reason, why :
https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster?newreg=471a9a26108243d78d4ca74a87e7a115
and also check this if you've hosted mongoDB on mongo Atlas:
https://docs.atlas.mongodb.com/unsupported-commands/
I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T
For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is
mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want
This may be because you havent set noAuth=true in mongodb.conf
# Turn on/off security. Off is currently the default
noauth = true
#auth = true
After setting this restart the service using
service mongod restart

Using "meteor mongo" on localhost but with remote Database

I'm following the telescope tutorial.
I created a /client/collections/myfile.js
I'm on localhost, but I'm launching Meteor with remote DB hosted on MongoHQ instead of using Meteor's local DB.
In this tutorial I'm told to insert a new post by opening the Mongo console.
$ meteor mongo
How can I:
$ meteor mongo (somehow connect to my remote DB to use the meteor commands in terminal
So that I can:
$ db.collectionname.insert({ stuff });
Or does this have nothing to do with "Meteor" in this case and I just use a Mongo shell outside of Meteor? The collection that I created in "/client/collections/collection.js" is this simply for telling Meteor which collection to push as a subset to the client?
I'd like to use the same DB ( remotely hosted with MongoHQ) for my localhost development, and my actual live dev.mysite.com so when I deploy to this dev site, anything I've done in the DB is also there and ready to go.
Assuming you had a username of username, a password of PASSWORD, a database named test, and a hostname of hatch.mongohq.com:
Connecting via the shell
$ mongo hatch.mongohq.com:27017/test -u username -p PASSWORD
Connecting via Meteor
$ MONGO_URL="mongodb://username:PASSWORD#hatch.mongohq.com:27017/test" meteor
Other notes
You should define your Meteor collections outside of the client directory so they can be used on both the client and the server. See this for more details.
You will find that connecting to a remote database is much slower than connecting locally, so it's generally not recommended for development.
Meteor creates a dev database for you when it starts. This also affords you the very helpful commands: meteor reset and meteor mongo, to reset, and connect to said database.
Initializing your database
Create a file on the server for initialization - e.g. server/initialize.js. When the server starts you can add users or other documents which do not yet exist. For example:
Meteor.startup(function() {
if (Meteor.users.find().count() === 0) {
Accounts.createUser({
username: 'jsmith',
password: 'password',
profile: {
firstName: 'John',
lastName: 'Smith'
}
});
}
});