mongo shell command not accept use db command - mongodb

i am trying to pull records form mongo data base with json format to do that i am running below js :
conatin of get_DRMPhysicalresources_Data.js
cursor = db.physicalresources.find().limit(10)
while ( cursor.hasNext() ){
print( JSON.stringify(cursor.next()) );
}
the command i run to get the records :
mongo host_name:port/data_base_name -u user -p 'password' --eval "load(\"get_DRMPhysicalresources_Data.js\")" > DRMPhysicalresources.json
and i am able to get the result as josn formate inside DRMPhysicalresources.json , now i want to switch to other data base using use command i try add use db as below :
conatin of get_DRMPhysicalresources_Data.js
use db2_test
cursor = db.physicalresources.find().limit(10)
while ( cursor.hasNext() ){
print( JSON.stringify(cursor.next()) );
}
the command i run to get the records :
mongo host_name:port/data_base_name -u user -p 'password' --eval "load(\"get_DRMPhysicalresources_Data.js\")" > DRMPhysicalresources.json
but i am getting below errors :
MongoDB shell version v4.2.3
connecting to: "some data base info"
Implicit session: session { "id" : UUID("8c85c6af-ebed-416d-9ab8-d6739a4230cb") }
MongoDB server version: 4.4.11
WARNING: shell and server versions do not match
2022-04-11T13:39:30.121+0300 E QUERY [js] uncaught exception: SyntaxError: unexpected token: identifier :
#(shell eval):1:1
2022-04-11T13:39:30.122+0300 E QUERY [js] Error: error loading js file: get_DRMPhysicalresources_Data.js :
#(shell eval):1:1
2022-04-11T13:39:30.122+0300 E - [main] exiting with code -4
is there are any way to add use db2_test without break it ?

You can try this:
db = new Mongo().getDB("myOtherDatabase");
or
db = db.getSiblingDB('myOtherDatabase')
( this is the exact js equivalent to the 'use database' helper)
docs

Related

mongo db error - SyntaxError: missing ; before statement

when i try to run this command on cmd.
mongo test --eval 'db.testcollection.find({ createdate: {$gte: ISODate("2020-07-28 10:08:37.579Z"),$lt: ISODate("2020-08-04 13:42:40.975Z")}}, {place:1, _id:0}).forEach(function(x) { print(x.place); })'
it throws this error
MongoDB server version: 4.0.5
2020-08-06T13:33:49.336+0530 E QUERY [js] SyntaxError: missing ; before statement #(shell eval):1:19
i try to add a semicolon at the end. it still throws same error.
mongo test --eval 'db.testcollection.find({ createdate: {$gte: ISODate("2020-07-28 10:08:37.579Z"),$lt: ISODate("2020-08-04 13:42:40.975Z")}}, {place:1, _id:0}).forEach(function(x) { print(x.place); });'
Error is at line 1, column 19. So placing ; at the end will not solve the issue.
Could you use
mongo --eval 'db.testcollection.find({ createdate: {$gte: ISODate("2020-07-28 10:08:37.579Z"),$lt: ISODate("2020-08-04 13:42:40.975Z")}}, {place:1, _id:0}).forEach(function(x) { print(x.place); })' test
test is the db name where testcollection is present.

MongoDb - command drop requires authentication

I have the following command
mongo clean_collection.js --host localhost --username root --password example
Clean_collection.js file contains:
conn = new Mongo();
db = conn.getDB("MyDb");
var myColl = db.getCollection('MyCollection');
myColl.drop();
But MongoDb returns:
MongoDB shell version v4.2.8
connecting to: mongodb://localhost:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("22d094e1-fb65-46c8-a9e6-386c1678c680") }
MongoDB server version: 4.2.8
2020-07-15T10:33:00.787-0400 E QUERY [js] uncaught exception: Error: drop failed: {
"ok" : 0,
"errmsg" : "command drop requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
DBCollection.prototype.drop#src/mongo/shell/collection.js:696:15
I'm also using MongoDb .NET Driver and I can drop the collection withou any problems with using .NET driver.

MongoDB create collection failure

I am trying to
1. Create a database
use testdb switched to db testdb
2. Create collection
testdb.createCollection(testcollection)
I am getting following error:
2015-05-12T11:21:19.619-0700 E QUERY ReferenceError: testdb is not defined
at (shell):1:1
The correct way is by using the db.createCollection() method, your code fails because testdb is not a mongodb object in your call testdb.createCollection(testcollection). Try the following:
> use testdb
switched to db testdb
> db.createCollection("testcollection")
{ "ok" : 1 }
> db.getCollectionNames()
[ "system.indexes", "testcollection" ]
>

Pass a .js file to mongo db.eval()

I am trying to get variety working with db.eval() instead of commandline --eval. This is because I get some problems with authentication.
The normal use is from the commandline:
$ mongo test --eval "var collection = 'users', maxDepth = 3" /path/to/variety.js
What I am trying to do is this:
$ mongo
>> use admin
>> db.auth("foo", "bar")
>> use anotherColl
>> db.eval("/path/to/variety.js", "var collection = 'users', maxDepth = 3")
>> Thu Mar 7 13:19:10 uncaught exception: {
"errmsg" : "compile failed: JS Error: SyntaxError: invalid flag after regular expression nofile_a:0",
"ok" : 0
}
Is there a way to have db.eval() eat an javascript file instead of an string?
According to #Sammaye and my gut feeling you can't put in .js files in db.eval(). However for variety there is an solution described here.
mongo -u USER-p PASS admin --eval "var collection = 'COL', db_name='DB_NAME'" variety.js
And now the authentication problem :(

MongoDB with Authentication

I am trying to get MongoDB running on my localhost (Windows) with authentication.
To do so, I first have to add a user, right?
I did so by starting the daemon using this command:
C:\[…]\mongod.exe -f C:\[…]\mongo.config
mongo.config contains the following:
# Basic database configuration
dbpath = C:\[…]\db\
bind_ip = 127.0.0.1
port = 20571
# Security
noauth = true
# Administration & Monitoring
nohttpinterface = true
After that I connected via this command:
C:\[…]\mongo.exe --port 20571 127.0.0.1
There I added a user:
> use admin
switched to db admin
> db.addUser('test', 'test')
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }
{
"user" : "test",
"readOnly" : false,
"pwd" : "a6de521abefc2fed4f5876855a3484f5",
"_id" : ObjectId("50db155e157524b3d2195278")
}
To check if everything worked I did the following:
> db.system.users.find()
{ "_id" : ObjectId("50db155e157524b3d2195278"), "user" : "test", "readOnly" : false, "pwd" : "a6de521abefc2fed4f5876855a3484f5" }
Which seemed OK to me.
After that I changed "noauth = true" to "auth = true" in the mongo.config file and restarted the daemon.
Now I expected to be able to connect with user and password:
C:\[…]\mongo.exe --port 20571 -u test -p test 127.0.0.1
Which denied access to me with this message:
MongoDB shell version: 2.0.4
connecting to: 127.0.0.1:20571/127.0.0.1
Wed Dec 26 16:24:36 uncaught exception: error { "$err" : "bad or malformed command request?", "code" : 13530 }
exception: login failed
So here's my question: Why does the login fail?
I can still connect without providing user and password, but can't access any data because "unauthorized db:admin lock type:-1 client:127.0.0.1". Which is actually what I expected.
As Andrei Sfat told me in the comments on the question I made 2 major errors.
First, I thought I could pass the IP to the Client as a simple argument. But you have to use --host for that.
Instead, the parameter I thought was the IP address actually should be the db name.
So the correct command to connect to a Server is as follows:
C:\[…]\mongo.exe --port 20571 -u test -p test --host 127.0.0.1 admin
Second, users are per database. As I only added the user "test" to the db "admin", it only works there.
Obviously the auth = true configuration wasn't load successfully. Did you forget the -f paramter when you restart the mongod.exe?
C:\[…]\mongod.exe -f C:\[…]\mongo.config