MongoDb C# driver - test authentication mode - mongodb

Using the C# MongoDb driver, is there a way to query a server to find out if it was started with:
mongod --auth or just mongod?
Thanks.

There is a ticket on the MongoDB tracker indicating the getCmdLineOpts command can be used to get the auth mode of the server.
db.runCommand("getCmdLineOpts")
returns
{
"argv" : [
"mongod",
"--config",
"mongodb.conf"
],
"parsed" : {
"auth" : "true",
"config" : "mongodb.conf",
...
},
"ok" : 1
}
If --auth was passed on the command line it will appear in the argv and parsed nodes; if it was set in mongodb.conf it will only appear in the parsed node.

Related

"There are no users authenticated" even though authentication is disabled

I just downloaded the new MongoDB 4.2.1, on Windows, and I just want to use it locally without authentication. I am able to run mongod plain and the server starts fine. I am able to connect to mongodb://localhost:27017, but when I try to do anything I get the error there are no users authenticated.
I never had this issue in previous versions, so I'm wondering if 4.2 now has new restrictions that authentication must be enabled or something. Is that the case?
Edit: This is a new fresh install of MongoDB, and I've uninstalled all other versions. I haven't changed the config. All I have done is create the C:/data/db directory.
Edit 2:
Here is my config file:
storage:
dbPath: C:\Program Files\MongoDB\Server\4.2\data
journal:
enabled: true
net:
port: 27017
bindIp: 127.0.0.1
Some more information from messing around. MongoDB Compass gives me the error immediately upon connecting. A nodejs application is able to connect but when attempting to write anything it gets the error.
However, in the mongo shell I am able to connect and make write operations with no issues.
There are no commands being logged, only the initial startup output which all seems normal.
db._adminCommand( {getCmdLineOpts: 1}) output:
{
"argv" : [
"C:\\Program Files\\MongoDB\\Server\\4.2\\bin\\mongod.exe",
"--config",
"C:\\Program Files\\MongoDB\\Server\\4.2\\bin\\mongod.cfg",
"--service"
],
"parsed" : {
"config" : "C:\\Program Files\\MongoDB\\Server\\4.2\\bin\\mongod.cfg",
"net" : {
"bindIp" : "127.0.0.1",
"port" : 27017
},
"service" : true,
"storage" : {
"dbPath" : "C:\\Program Files\\MongoDB\\Server\\4.2\\data",
"journal" : {
"enabled" : true
}
},
"systemLog" : {
"destination" : "file",
"logAppend" : true,
"path" : "C:\\Program Files\\MongoDB\\Server\\4.2\\log\\mongod.log"
}
},
"ok" : 1
}
Well, for some reason it worked when connecting to 127.0.0.1 and not localhost. Never had that before.
I'm giving this as a "response" (instead of a "comment"), just so I can format things more clearly for you.
I happen to be running MongoDB 4.2.0 on a Linux VM, with no authentication ... and no problems.
SUGGESTIONS:
Check /etc/mongod.conf (Windows equivalent), and make sure authorizationis COMPLETELY COMMENTED OUT (vs. "authorization: disabled")
Check /var/log/mongodb/mongod.log (Windows equivalent). If you find anything "significant", please copy/paste it into your post.
In "mongo", type db._adminCommand( {getCmdLineOpts: 1}) and ensure your runtime configuration settings match what you expect them to be.
Please keep us posted what you find!
Make sure you have installed mongodb

mongodb show dbs listDatabases failed

I am new to mongo db.
I just installed mongo DB on my MAC,
After watching this Youtube Video
https://www.youtube.com/watch?v=pWbMrx5rVBE&t=369s
In mongo shell, I entered show dbs and I get wired output.
Kindly help me to understand and solve this
> show dbs
2017-09-11T02:45:34.298+0530 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "unable to open cursor at URI statistics:table:collection-2-2362555297355466682. reason: No such file or directory",
"code" : 43,
"codeName" : "CursorNotFound"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:62:1
shellHelper.show#src/mongo/shell/utils.js:769:19
shellHelper#src/mongo/shell/utils.js:659:15
#(shellhelp2):1:1
After a couple of research, I found the solution and sharing all I learned so no new learner struggles like me.
My mistake :
I was staring mongodb using :
mongod --config "c:\MongoDB\Mongod.cfg"
and start mongo shell by just running
mongo
Starting Mongo DB and Shell
Then understood, what each command does :
|*| Start Mongo DB with default config :
mongod
|*| Start Mongo DB with config file :
mongod -f "c:\MongoDB\Mongods.cfg"
|Or|
mongod --config "c:\MongoDB\Mongod.cfg"
|O| Start Mongo DB with config flags :
mongod --dbpath "c:\mongodb\data\nameMdb" --logpath "c:\mongodb\log\nameMdbLog.log" --directoryperdb --logappend
So correspondingly we should use mongo also to start shell :
|*| Start Mongo shell with default config :
mongo
|*| Start Mongo shell with localhost config flags :
mongo --host localhost --port 28888
|*| Start Mongo shell with public config flags and user details :
mongo --username <user> --password <pass> --host <Host.IP.Adrs> --port 28888
|*| Creating Config File is explained here with example :
https://github.com/mongodb/mongo/blob/master/rpm/mongod.conf
I had a similar issue when configuring MongoDB for replication.
When I run the command below:
mongo
show dbs
I get the error:
> show dbs
uncaught exception: Error: listDatabases failed:{
"topologyVersion" : {
"processId" : ObjectId("60ddea05beb1d89d4d139546"),
"counter" : NumberLong(0)
},
"ok" : 0,
"errmsg" : "not master and slaveOk=false",
"code" : 13435,
"codeName" : "NotPrimaryNoSecondaryOk"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs/<#src/mongo/shell/mongo.js:147:19
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:99:12
shellHelper.show#src/mongo/shell/utils.js:937:13
shellHelper#src/mongo/shell/utils.js:819:15
#(shellhelp2):1:1
Here's how I fixed it:
The issue was that I had enabled the replication feature in the /etc/mongod.conf file without initializing the replication, so MongoDB could not tell which replica was the primary replica or secondary replica.
All I had to do was to comment out the replication feature in the /etc/mongod.conf file since I was not yet ready to set up replication:
#replication
# replSetName: my-replica-set-name
After which I restarted the MongoDB server:
sudo systemctl restart mongod
This time the command ran fine.
I experienced this issue today, installing the latest version of MongoDB with Homebrew and then launching the mongo shell and entering the command "show dbs". I tested this multiple times and spent some time researching it. The symptoms match an issue that was reported here: https://jira.mongodb.org/browse/SERVER-20753 where the issue was described as building WiredTiger separately from MongoDB and using an out of date version of WiredTiger.
While this is not the case for what you and I have experienced (note that Homebrew is currently installing 3.4.9 and WiredTiger 2.9.2), I guessed that it could be a similar mismatch between WiredTiger and MongoDB, so I decided to try installing a different version.
I ended up installing the latest "dev" version using this Homebrew command:
brew install mongodb --devel
This installs MongoDB 3.5.13 and WiredTiger 3.0.0 which do not have the issue. Note that 3.4.9 was released the day you reported this issue and 3.5.13 was released the next day, although 3.4.9 is still the current community edition listed here: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
In my case, the problem was replSet name.
I was changed my hostname at the Sharing preference and it was different with the previous installed replSet config's host name.
You can see the rs.config() in mongo shell like this.
"members" : [
{
"_id" : 0,
"host" : "MBA.local:27777",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
See the host: section and change it by rs.config({object}) command in mongo shell,
or just add the line below at the /etc/hosts file.
127.0.0.1 MBA.local

kaa monogodb in authentication mode

kaa-node throws following ERROR in the log file:
Command failed with error 13: 'not authorized on kaa
to execute command { createIndexes: "endpoint_registration",
user "mongokaa" creadted in db kaa, role = dbOwner
db.getUsers() [
{
"_id" : "kaa.mongokaa",
"user" : "mongokaa",
"db" : "kaa",
"roles" : [
{
"role" : "dbOwner",
"db" : "kaa"
}
]
}]
mongodb started with
mongod --quiet --config /etc/mongod.conf
athentication credentials are set on the Log appender configuration page
Why kaa-node kan't execute the command "createIndexes"?
The command can be executed over mongodb shell when I'm logged in with the user "mongokaa".
mongodb version: 3.2
ubuntu version: 16.0.4 LTS
kaa-node version: 0.10.0
Thank you for your help.
Currently, Kaa is not supported MongoDB version 3.2. See Kaa requirements and supported versions in our pre-release documentation. You can try MongoDB 2.6.9 version.

How to convert a MongoDB replica set to a stand alone server

Consider, I have 4 replicate sets and the config is as follows:
{
"_id": "rs_0",
"version": 5,
"members" : [
{"_id": 1, "host": "127.0.0.1:27001"},
{"_id": 2, "host": "127.0.0.1:27002"},
{"_id": 3, "host": "127.0.0.1:27003"},
{"_id": 4, "host": "127.0.0.1:27004"}
]
}
I am able to connect to all sets using
mongo --port <port>
There are documents for getting information on Convert a Standalone to a Replica Set, but can anyone tell me how to convert back to standalone from replica set?
Remove all secondary hosts from replica set (rs.remove('host:port')), restart the mongo deamon without replSet parameter (editing /etc/mongo.conf) and the secondary hosts starts in standalone mode again.
The Primary host is tricky one, because you can't remove it from the replica set with rs.remove.
Once you have only the primary node in the replica set, you should exit mongo shell and stop mongo. Then you edit the /etc/mongo.conf and remove the replSet parameter and start mongo again.
Once you start mongo you are already in standalone mode, but the mongo shell will prompt a message like:
2015-07-31T12:02:51.112+0100 [initandlisten] ** WARNING: mongod started without --replSet yet 1 documents are present in local.system.replset
to remove the warning you can do 2 procedures:
1) Droping the local db and restarting mongo:
use local
db.dropDatabase();
/etc/init.d/mongod restart
2)Or if you don't want to be so radical, you can do:
use local
db.system.replset.find()
and it will prompt a message like:
{ "_id" : "replicaSetName", "version" : 1, "members" : [ { "_id" : 0, "host" : "hostprimary:mongoport" } ] }
then you will erase it using:
db.system.replset.remove({ "_id" : "replicaSetName", "version" : 1, "members" : [ { "_id" : 0, "host" : "hostprimary:mongoport" } ] })
and it will probably prompt:
WriteResult({ "nRemoved" : 1 })
Now, you can restart the mongo and the warning should be gone, and you will have your mongo in standalone mode without warnings
Just remove a host from replica set (rs.remove('host:port')), relaunch it without replSet parameter and it's standalone again.
On an Ubuntu Machine
Stop your mongo server
open /etc/mongod.conf
Comment the replication and replSetName line
#replication:
#replSetName: rs0
Start your mongo server and go to mongo shell
drop local database
use local
db.dropDatabase()
Restart mongo
The MongoDB Documentation suggests the following to perform maintenance on a replica set member, which brings the the replica set member into standalone mode for further operations. With little modification it can be made standalone:
If node in concern is the only node in a shard, drain the chunks to other shards as per MongoDB documentation here, or else the sharded database will break, i.e.
Make sure balancer is enabled by connecting to mongos and run sh.startBalancer(timeout, interval)
For the shard in concern, go to admin database and db.adminCommand( { removeShard: "mongodb0" } )
Check draining status by repeating above removeShard command, wait for draining to complete
If node in concern is primary, do rs.stepDown(300)
Stop the node by running db.shutdownServer()
Change the yaml config by:
commenting out replication.replSetName (--replSetName in command line)
commenting out sharding.clusterRole for shard or config server (--shardsvc and --configsvr in command line)
commenting out net.port, then change it to a different port (--port in command line)
Start the mongod instance
If change is permanent, go to other mongod instance and run rs.remove("host:port")
After this, the node in concern should be up and running in standalone mode.
Follow below steps :
Go to mongo shell on Secondary servers
Stop the secondary servers by using below command :
use admin
db.shutdownServer()
Go to Linux shell- on secondary servers and type below command :
sudo service mongod stop
Starting the MongoDB replication -
Go to Linux shell - on secondary servers and type below command :
sudo service mongod start
Starting the MongoDB replication -
Go to primary and type below commands to start the replication :
a] rs.initiate()
b] rs.add("Secondar -1:port no")
c] rs.add("Secondary-2:port no")
d] rs.add({ "_id" : 3, "host" : "Hidden_member:port no", "priority" : 0,
"hidden" : true })
e] rs.status()

how can I see what ports mongo is listening on from mongo shell?

If I have a mongo instance running, how can I check what port numbers it is listening on from the shell? I thought that db.serverStatus() would do it but I don't see it. I see this
"connections" : {
"current" : 3,
"available" : 816
Which is close... but no. Suggestions? I've read the docs and can't seem to find any command that will do this.
You can do this from the Operating System shell by running:
sudo lsof -iTCP -sTCP:LISTEN | grep mongo
From the system shell you can use lsof (see Derick's answer below) or netstat -an to view what a process is actually doing. However, assuming you only have access to the mongo shell (which your question title implies), then you can run the serverCmdLineOpts() command. That output will give you all the arguments passed on the command line (argv) and the ones from the config file (parsed) and you can infer the ports mongod is listening based on that information. Here's an example:
db.serverCmdLineOpts()
{
"argv" : [
"./mongod",
"-replSet",
"test",
"--rest",
"--dbpath",
"/data/test/r1",
"--port",
"30001"
],
"parsed" : {
"dbpath" : "/data/test/r1",
"port" : 30001,
"replSet" : "test",
"rest" : true
},
"ok" : 1
}
If you have not passed specific port options like the ones above, then the mongod will be listening on 27017 and 28017 (http console) by default. Note: there are a couple of other arguments that can alter ports without being explicit, see here:
https://docs.mongodb.org/manual/reference/configuration-options/#sharding.clusterRole
Try this:
db.runCommand({whatsmyuri : 1})
It will display both the IP address and the port number.
MongoDB only listens on one port by default (27017). If the --rest interface is active, port 28017 (27017+1000) will also be open handling web requests for details.
MongoDB supports a getParameter command, but that only works if you're already connected to the Database (at which point you already know the port).
You can try, from the mongo shell:
db.getMongo()
Use this command to test that the mongo shell has a connection to the
proper database instance.
connection to <IP>:<PORT>
db.collection.explain()
For unsharded collections, explain returns the following serverInfo
information for the MongoDB instance:
"serverInfo" : {
"host" : <string>,
"port" : <int>,
"version" : <string>,
"gitVersion" : <string>
}
Default MongoDB Port