Sim
Sim

Reputation: 13538

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.

Upvotes: 12

Views: 8829

Answers (3)

Jose Quijada
Jose Quijada

Reputation: 690

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.

Upvotes: 3

Bhoju
Bhoju

Reputation: 71

This is quite old question, however still relevant, so answering.

One can use printjsononeline().

Upvotes: -3

Sim
Sim

Reputation: 13538

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.

Upvotes: 4

Related Questions