2

I am learning mongoDB by following the tutorial, http://docs.mongodb.org/manual/tutorial/getting-started/

However, the sample code, var c = db.testData.find(), confuses me. Without var, the execution just prints out the documents, with the var, c becomes the cursor. The other command, j = { name : "mongo" }, I don't see the difference with or without var. I want to be clear when I should have var and when I can ignore var.

I google the question little bit, for example, Difference between using var and not using var in JavaScript, it talks about scope. I cannot understand how my question relates to scope.

Community
  • 1
  • 1
Dino Tw
  • 3,167
  • 4
  • 34
  • 48

2 Answers2

3

http://docs.mongodb.org/manual/tutorial/iterate-a-cursor/

According to this doc,

However, 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 in the results.

Yang
  • 86
  • 1
  • 8
  • It's still not clear for me. I can assign variable with or without var in other command, for example, `var j = { name : "mongo" }` vs `j = { name : "mongo" }`. I don't see the difference in execution. – Dino Tw Jan 13 '14 at 22:43
  • Ok, forget about what I put there before, here's what mongodb says: http://docs.mongodb.org/manual/tutorial/iterate-a-cursor/, search for 'var keyword' – Yang Jan 13 '14 at 22:49
  • Yup, according the the documentation, it's designed to work in this way. Thank you for sharing the link. – Dino Tw Jan 13 '14 at 23:01
1

From the mongo getting started tutorial:

This tutorial provides an introduction to basic database operations using the mongo shell. mongo is a part of the standard MongoDB distribution and provides a full JavaScript environment with a complete access to the JavaScript language and all standard functions as well as a full database interface for MongoDB. See the mongo JavaScript API documentation and the mongo shell JavaScript Method Reference.

Source: http://docs.mongodb.org/manual/tutorial/getting-started/

In Javascript it's best practice to not use global variables. You define global variables without the var prefix and local variables with the var prefix. I guess the Javascript implementation in Mongo disabled global variables completely because it's bad practice.

gitaarik
  • 42,736
  • 12
  • 98
  • 105
  • I found the discussion on this topic in the link I mentioned, but I could not figure it out how my question relates to local or global variable. – Dino Tw Jan 13 '14 at 22:46