Skip to content

Instantly share code, notes, and snippets.

@osroca
Last active September 2, 2016 16:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save osroca/4327517 to your computer and use it in GitHub Desktop.
Save osroca/4327517 to your computer and use it in GitHub Desktop.
[How to] embed javascript libraries into the mongo shell

From https://education.10gen.com/courses/10gen/M101/2012_Fall/wiki/how-embed-javascript-libraries-into-mongo-shell/_edit/

There is obviously no <script src="..">; in mongo shell, nor is there an "include" or "run" command.

Let's say, I'd like to embed the follwing libraries:

underscore.js
xdate.js
xdate.i18n.js

I put theses files in a directory and rename them to make sure to load them in correct order (and make sure that they are utf-8 encoded!):

i01-underscore.js
i11-xdate.js
i12-xdate.i18n.js

now, start mongo shell (from that directory):

mongo [db] --shell i*.js

note: you may give a db name to connect to before the --shell, and don't use input redirection (less than) before the files.

now, you can do things like this:

ronald@ronald:~/m0101/libs_for_shell$ mongo --shell i*.js
MongoDB shell version: 2.2.1
connecting to: test
type "help" for help
loading file: i01-underscore-min.js
loading file: i11-xdate.js
loading file: i12-xdate.i18n.js
> use blog
switched to db blog
> doc = db.posts.findOne()
{
  "_id" : ObjectId("50a0e4b18cde4b5cd1000001"),
	"body" : "this is the first test",
	"permalink" : "test_number_one",
	"author" : "ronald",
	"tags" : [
		"mongodb",
		"test"
	],
	"date" : ISODate("2012-11-12T11:59:45.048Z"),
	"title" : "test number one"
}
> _.keys(doc)
[ "_id", "body", "permalink", "author", "tags", "date", "title" ]
> new XDate(doc.date).toString("dd MMMM yyyy","pt")
12 Novembro 2012
> new XDate(doc.date).addWeeks(2).toString("MMMM, dd yyyy")
November, 26 2012
> 
@jwerre
Copy link

jwerre commented Jul 1, 2015

Why not just load('underscore.js')?

@rjurney
Copy link

rjurney commented Jan 27, 2016

Because you rent a mongo server and don't have shell access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment