Asynchronous cursor change from mongo

Hello, I noticed an interesting change in the functionality of mongosh versus mongo that I did not see covered in documentation. It appears mongosh handles a cursor asynchronously and I would like to know how to set it to synchronous like the original mongo shell.

Example

let curs = db.test.find()
curs.forEach(function(item){
   print("1")
   print("2")
})

original mongo shell output for 3 documents

1
2
1
2
1
2

mongosh output for 3 documents

1
1
1
2
2
2

I am not too sure, but I suspect that your issue is more about print() being async rather than the cursor.

You may try with await print(...) or do something that is not async.

You should not assume that print is synchronized in any languages. It is common to relinquish during I/O.

unfortunately await, while reserved, has not been implemented yet (at least in mongosh 5.0.2).

Oups!

“Saru mo ki kara ochiru”

But here an alternative:

mongosh> c.find()
{ _id: 1, v: 2 }
{ _id: 3, v: 4 }

mongosh> let output = []
mongosh> let cursor = c.find().sort( { _id : 1 })
mongosh> cursor.forEach( function(item) {
  output.push( "_id " + item._id ) 
  output.push( "v " + item.v )
} )
mongosh> output.forEach( function(line) { print( line ) })
'_id 1'
'v 2'
'_id 3'
'v 4'

That is a good alternative if my goal was to express some sort of output. In this case, when I am testing a more complex mongo script, it’s useful to get some feedback of what is going on so I can debug the issue. For example, in the old mongo shell. I might have something like

c.find().forEach(function(element) {
  print("handling element: " + element)
  print("some other information for debugging purposes")
  //mutate element
})

In this case I need the log to be handled synchronously with the rest of the script. Since mongosh differs from the old mongo shell in making their stdout async, but does not provide standard scheduling/ methodologies like await, it seems that there is a rather large difference between these two shells that cannot yet be rectified with the current functionality.

What version of mongosh are you using?

I don’t seem to be able to reproduce the problem.