Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paginate output inside mongo shell

Is it possible to pipe results in to a pager from within a mongo shell?

The mysql cli equivalent would be:

mysql> pager less

like image 775
davidmh Avatar asked Apr 20 '14 06:04

davidmh


People also ask

How do I run a JavaScript script in mongo shell?

Load JavaScript file js file from mongo shell, using the load() function. load() function allow to execute from absolute and relative paths. We can simply load a file in mongo shell with load() function. And Finally If we have lots of scripted files, We can load() inside another javaScript file.

How do I print a variable in mongo shell?

You can execute Java Script in Mongo CLI or command prompt The print() method simply prints the data arguments that are passed into it. print("Hello From Mongo"); eg: print(data, ...); printjson(object); print(JSON.

How use mongo shell in CMD?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.


3 Answers

You can try to use mongo --eval option. Something like:

mongo <db> --quiet --eval '<query>' | less
like image 130
Mike Shauneu Avatar answered Nov 07 '22 20:11

Mike Shauneu


Mongo shell already paginates the results if the returned cursor is not assigned to a variable. From the documentation:

...in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Type it to iterate another 20 times.

You can set the DBQuery.shellBatchSize attribute to change the number of iteration from the default value 20.

like image 42
Christian P Avatar answered Nov 07 '22 19:11

Christian P


It doesn't seem possible, but you can output to a file, and then read your file with a pager in another terminal:

$ mongo | tee file.txt

See Printing Mongo query output to a file while in the mongo shell.

like image 27
Xavier Lamorlette Avatar answered Nov 07 '22 20:11

Xavier Lamorlette