Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB shell: printing to console without a trailing newline?

Is there a way to write to STDOUT without a trailing newline from the Mongo shell? I can't seem to find anything other than print() available.

like image 428
Sim Avatar asked Jul 04 '12 23:07

Sim


2 Answers

This is related to my SO question on reading a line from the console. Per @Stennie's comment, it is not possible in the current (2.0.6) version of the Mongo shell.

like image 157
Sim Avatar answered Sep 27 '22 22:09

Sim


There might be ways to work around it. You can accumulate the results in an intermediate variable (could be an array, string or any other data structure), then print the entire thing in a single line. Below example illustrates use of an array to capture values from query results, then array is converted to string with comma as a separator. In my case I'm interested in just the _id field:

var cursor = db.getCollection('<collection name>').find(<your query goes here>)
let values = []
cursor.forEach((doc) => values.push(doc._id))
print(values.join(','))

Depending on how many results you're expecting, not sure if space consumed by the intermediate data structure might overwhelm memory. If that's the case can craft the query to return smaller, subsets of data that when added together comprise the full result set you're going for.

like image 45
Jose Quijada Avatar answered Sep 27 '22 23:09

Jose Quijada