1

what is the difference between two mongo queries.

db.test.find({"field" : "Value"})

db.test.find({field : "Value"})

mongo shell accepts both.

Adeel Ahmad
  • 1,671
  • 1
  • 17
  • 22
  • it has nothing to do with mongo, it is how you define your json. have a look here http://stackoverflow.com/questions/4348478/what-is-the-difference-between-object-keys-with-quotes-and-without-quotes – anvarik May 12 '14 at 10:53
  • Thanks for clearing this out. – Adeel Ahmad May 12 '14 at 11:46

3 Answers3

3

There is no difference in your example.
The problem happens when your field names contain characters which cannot be a part of an identifier in Javascript (because the query engine is run in a javascript repl/shell)
For example user-name because there is a hyphen in it.
Then you would have to query like db.test.find({"user-name" : "Value"})

Munim
  • 6,310
  • 2
  • 35
  • 44
1

For the mongo shell there is no actual difference, but in some other language cases it does matter.

The actual case here is presenting what is valid JSON, and with myself as a given example, I try to do this in responses on this forum and others as JSON is a data format that can easily be "parsed" into native data structures, where alternate "JavaScript" notation may not be translated so easily.

There are certain cases where the quoting is required, as in:

 db.test.find({ "field-value": 1 })

or:

 db.test.find({ "field.value": 1 })

As the values would otherwise be "invalid JavaScript".

But the real point here is adhering to the JSON form.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • Thank you for clarification, so this is more related to JSON. – Adeel Ahmad May 12 '14 at 11:43
  • @AdeelAhmad in general then that is the case. But specifically as per additional examples given, you need to "quote" this way even with JavaScript syntax or the syntax itself will be invalid. But the general concept is valid JSON and is a good practice to follow. – Neil Lunn May 12 '14 at 11:52
1

You can understand with example: suppose that you have test collection with two records

{ '_id': ObjectId("5370a826fc55bb23128b4568"), 'name': 'nanhe' }

{ '_id': ObjectId("5370a75bfc55bb23128b4567"), 'your name': 'nanhe' }

db.test.find({'your name':'nanhe'});

{ "_id" : ObjectId("5370a75bfc55bb23128b4567"), "your name" : "nanhe" }

db.test.find({your name:'nanhe'});

SyntaxError: Unexpected identifier

Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71