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.
Related
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
I have this issue with my meteor app. When I run this query on my chrome console, It returns the expected data
Questions.find({}, {sort:{commentLength: -1}})
but when I run it in the console as db.questions.find({}, {sort:{commentLength: -1}})
it returns this error
error: {
"$err" : "Can't canonicalize query: BadValue Unsupported projection option: sort: { commentLength: -1.0 }",
"code" : 17287
}
Why does this error happen? Thanks
sort has a different syntax when executed in a mongodb shell. Try this instead:
db.questions.find().sort({commentLength: -1})
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" ]
>
Here is an example query:
db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count()
Query works in the mongo shell. However, in a bash script or directly in the Ubuntu shell
mongo fivemin --eval "printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())"
returns a SyntaxError: missing : after property id (shell eval):1
I can't seem to find a problem with the query. I reverted to { "_id" : {"s" : ...} }, and it still gives the same problem. find().count() works however.
Had the same issue in bash shell.
This will fail because of double quotes:
mongo fivemin --eval "printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())"
But using the eval string in single quote it works:
mongo fivemin --eval 'printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())'
And if you use a $ sign like $regex you need to escape it:
mongo fivemin --eval 'printjson(db.readings.find( {"_id.s" : {"\$regex":"2012-11-01T*"} } ).count())'
use single quotes into double,
e.g.:
mongo fivemin --eval "printjson(db.readings.find( {'_id.s' : ISODate('2012-11-01T00:05:00Z') } ).count())"
There is also another possible issue using --eval with bash double quotes, if the query contains mongo operators i.e. $ne, $gt etc, since operators start with $.
double quotes:
$ echo " '$ne': null "
$ => '': null
single quotes:
$ echo ' "$ne": null '
$ => "$ne": null
Bash tries to replace these operators with variables.
$ ne = 'test'
$ echo " '$ne': null "
$ => 'test': null
So, I always recommend to use --eval with single quotes.
Just sat and thought about it. It seems to be a problem with bash exiting out on the " (should have noticed immediately!). Instead I used ' (or I guess you can use /" for JSON) so the query looks like:
printjson(db.readings.find({'_id.s' : ISODate('2013-01-01T00:05:00Z') }).count())"
The best way to handle this is to build the mongo command in a var. Then use eval command to execute the mongo command:
mongo_update_query="db.collectionName.update({ name:\""${some_name}"\", \
{ \$addToSet: { nick_names : { \$each : [ ${name_array} ] }}});"
mongo_cmd_str=$(echo "mongo --host ${mongo_host} --port ${mongo_port} ${mongo_database} --eval '${mongo_update_query}'")
# the actual call to mongo query
eval ${mongo_cmd_str}
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 :(