How to run a javascript file inside a mongo shell after connection - mongodb

I have a javascript file and want to run them inside a mongo shell. I know how to load the javascript file during connection from this link: How to execute mongo commands through shell scripts?.
But my case is how to run an external js file after the connection already established.
My js file looks like below:
db.getSiblingDB("test")
.enron_messages.find({
$or: [{ filename: "111." }, { "headers.From": "test#gmail.com" }]
})
.sort({ "headers.To": 1 })
.limit(10);
and in my mongo shell, I use load('test.js') to load that file but it returns true(see below output). How to execute this file?
> load('test.js')
true

The load() function does in fact execute the javascript file. The problem you are facing is that when the external scripts are executed in "scripted" mode, find() will only return the cursor and not iterate it as the mongo shell does when run in Interactive mode.
This behavior is detailed in the docs in Write Scripts for the Mongo shell. There you will see an example of how you need to iterate the cursor and print the results:
cursor = db.collection.find();
while ( cursor.hasNext() ) {
printjson( cursor.next() );
}

Related

HOw to upload large content html under an array in monogodb through cmd

I have an structure like this:
{
"_id" : ObjectId("5f31183723406c2ad8b72e7e"),
content: ["<h3 class=\"ql-align-justify\">Hello world<h3>"]
}
Now When update content field through cmd and replace the content with large content then on cmd, mongodb will not fully copy the string and generates error
uncaught exception: SyntaxError: "" literal not terminated before end of script :
On my development machine I have a robo mongo GUI so I will directly update the content and things are fine.
But on server I have to do all this things through terminal and I am facing the error.
Command which I am using is
db.CollectionName.updateOne({_id: ObjectId('5f31183723406c2ad8b72e7e')}, {$set: {content: ["here my large content of html"]}})

How to execute mongo commands through shell scripts? (mine does not work)

I am trying to use scripts js in the mongo shell. I am reading a book on the topic. I have tried several options, such as opening the cmd at a specific place at my computer.
I found here the question "How to execute mongo commands through shell scripts?", but nothing seems to work for me. My mongo is working properly and I can enter mongo simply typing mongo at cmd. However, it cannot find the js files.
I am using Windows; anything has an idea what may be happening under the hood?
An example after:
mongo demo.js
2020-02-20T11:03:33.098-0300 E - [main] file [demo.js] doesn't exist
2020-02-20T11:03:33.098-0300 F - [main] failed to load: demo.js
2020-02-20T11:03:33.098-0300 E - [main] exiting with code -3
Create your my_script.js file with this one command:
db.testColl.insertOne( { a: "hello" } )
Place the script file in your current directory.
1. Run JS Script from OS Command-line:
From OS prompt do this:
> mongo localhost/testDB my_script.js
Once the above command is run, you will see the output as follows (similar, depending upon your MongoDB version and the OS (Windows, in this case)):
MongoDB shell version v4.2.3
connecting to: mongodb://localhost:27017/testdb?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("456b350f-668f-4389-9901-7c456e2c50fe") }
MongoDB server version: 4.2.3
Now, from the Mongo Shell (i.e., do mongo, and then from the mongo prompt):
mongo > use testDB
mongo > show collections
You will see the testColl listed.
mongo > db.testColl.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
This is the document created in the testDB database and the collection testColl as per the command in the my_script.js.
2. Run JS Script from Mongo Shell:
Also, you can run the my_script.jsfrom within the Mongo Shell.
mongo > load("my_script.js")
true
mongo > db.test.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }
See there are two documents with different _id field values.
NOTE: I think you can run only some commands from the .js file.
3. Another Example:
Create a JS file named script2.js with the following content:
db.test.find().forEach(printjson)
Note the printjson shell method prints a document to the shell output.
mongo > load("script2.js")
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }
References:
load()
Print document value in
MongoShell

MongoDB - A Script to Create Indexes

New to MongoDB - at the moment I'm creating indexes directly from my web app however I want to instead have some sort of bash script I run (and more easily maintain) that can create my various text indexes for me.
Wanted to check is this possible? I'm unsure about how I would actually execute it if so - namely I have a Docker image running Docker - so do I have to bash into that then run the .sh? Or would I just specify the DB and collection in the script itself and just run it from terminal as usual?
Any pointers would be appreciated.
Thanks.
You can do it using java script:
var createIndexes = function(fullObj) {
conn = new Mongo();
db = conn.getDB(databaseName);
getMapInd = null;
setMapInd1 = db.testMappings.createIndex( { 'testId': 1}, {unique: true} )
getMapInd = db.testMappings.getIndexes();
printjson("---------------------Below indexes created in Mappings collection-----------------------");
printjson(getMapInd);
};
createIndexes();

mongo --shell file.js and "use" statement

can't find solution for simple question:
I have file text.js
use somedb
db.somecollection.findOne()
When I run this file in cmd with redirection command from file:
"mongo < text.js"
it's work properly
But when I try this way
"mongo text.js" or "mongo --shell test.js"
I got this error message
MongoDB shell version: 2.2.0
connecting to: test
type "help" for help
Wed Dec 05 16:05:21 SyntaxError: missing ; before statement pathToFile\test.js.js:1
failed to load: pathToFile\test.js.js
It's fail on "use somedb". If I remove this line, it's run without error, but console is clear.
is there any idea, what is this and how to fix?
I'm tying to find sollution for this, to create build tool for Sublime Text 2.
default build file was
{
"cmd": ["mongo","$file"]
}
but in this case I get the error above
PS. right after posting this question I find sollution for SublimeText2:
{
"selector": "source.js",
"shell":true,
"cmd": ["mongo < ${file}"]
}
PSS. right after posting this question I find sollution for SublimeText3:
{
"selector": "source.js",
"shell":true,
"cmd": ["mongo","<", "$file"]
}
this build tool work properly
use dbname is a helper function in the interactive shell which does not work when you are using mongo shell with a JS script file like you are.
There are multiple solutions to this. The best one, IMO is to explicitly pass the DB name along with host and port name to mongo like this:
mongo hostname:27017/dbname mongoscript.js // replace 27017 with your port number
A better way to do this would be to define the DB at the beginning of your script:
mydb=db.getSiblingDB("yourdbname");
mydb.collection.findOne();
etc.
The latter is preferable as it allows you to interact with multiple DBs in the same script if you need to do so.
You can specify the database while starting the mongo client:
mongo somedb text.js
To get the output from the client to stdout just use the printjson function in your script:
printjson(db.somecollection.findOne());
Mongo needs to be invoked from a shell to get that mode, with Ansible you would have this:
- name: mongo using different databases
action: shell /usr/bin/mongo < text.js
Instead of this:
- name: mongo breaking
command: /usr/bin/mongo < text.js
This is what finally worked for me on Windows + Sublime Text 2 + MongoDB 2.6.5
{
"selector": "source.js",
"shell":true,
"cmd": ["mongo","<", "$file"],
"working_dir" : "C:\\MongoDB\\bin"
}

cannot mongodb console in OSX using mongoose

i am able to run mongodb in my apple console, and vim the mongo.log
right now, i just want to open up the mongodb console so that i can test queries in the console just like the examples in http://www.mongodb.org/display/DOCS/Tutorial
at the moment, the cursor is not returned:
> mongodb
all output going to :/usr/local/var/log/mongodb/mongo.log
and the cursor is not returned. i was expecting the cursor to be returned to so i can do the following :
> mongodb
all output going to :/usr/local/var/log/mongodb/mongo.log
> test = {name : "bouncingHippo"}
> db.family.save(test)
> "ok"
What am i doing wrong? i am using mongoose
I'm not entirely clear which console you are getting this output from, as the Node console won't return anything usable if you just enter mongodb.
If what you are trying to do is just launch a MongoDB console, you will need to first launch the mongod process and then attach to that process with the MongoDB console. The MongoDB console is called mongo. In the simplest test, you can launch mongod from one terminal window and then mongo from another. In the terminal window that is running mongo you can then work through the examples in the tutorial. Your pseudo code would then look like:
MongoDB shell version: 2.2.1
connecting to: 127.0.0.1:18070/test
> test = {name : "bouncingHippo"}
{ "name" : "bouncingHippo" }
> db.family.save(test)
If you are trying to use Mongoose for the pseudo code you have in your question, it would be more like the following from the Node console (assuming Node.js and Mongoose are installed)
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://localhost/test');
var testSchema = new mongoose.Schema({
name: String
})
var Test = db.model('Test', testSchema)
var test = new Test({ name: 'bouncinghippo' })
test.save()