Aggregation method returns fields in array in single not double quotes

Here is a query from the MongodB unviersity Basic course training and what is returned when I execute the query using MongodB shell. The fields in the returned array are in single quotes. The presentation of the online tutorial for this query displays double quotes for the fields which is what I was expecting. Can someone tell me why I am getting single quotes and/or how I can change it to return double quotes? Thanks. Mike M.

sample_airbnb> db.listingsAndReviews.aggregate([{$project:{"address":1,"_id":0}},{$group:{_id: "$address.country"}}])
[
  { _id: 'Turkey' },
  { _id: 'China' },
  { _id: 'Hong Kong' },
  { _id: 'Australia' },
  { _id: 'United States' },
  { _id: 'Brazil' },
  { _id: 'Spain' },
  { _id: 'Portugal' },
  { _id: 'Canada' }
]

Hi @Michael_McGrath welcome to the community!

Technically there is no difference between single or double quotes, so it doesn’t really make a difference since Javascript accepts both as string delimiters.

Note that this is different than JSON, since JSON only accepts double quotes as string delimiters. However if you’re working in the mongosh shell, it makes no difference.

Best regards
Kevin

Welcome to the MongoDB Community @Michael_McGrath !

As @kevinadi mentions,. matching single quotes or double quotes can both be used to enclose string values in JavaScript so the data values are equivalent.

What you observed is a difference in the output of the legacy mongo shell used in the current course videos versus the newer MongoDB Shell (mongosh) which is now the recommended shell environment.

mongosh tries to be smarter about quoting to avoid having to escape single/double quotes.

If I insert:

 db.data.insertOne({thing: ['Users', '"Users"', "User's", 'User"s']})

Output in the legacy mongo shell always uses double quotes:

db.data.findOne()
{
	"_id" : ObjectId("634f8c8bef83f38d54a2a10e"),
	"thing" : [
		"Users",
		"\"Users\"",
		"User's",
		"User\"s"
	]
}

The same query in mongosh uses either single or double quotes so you don’t see escaped quotes like \".

db.data.findOne()
{
  _id: ObjectId("634f8c8bef83f38d54a2a10e"),
  thing: [ 'Users', '"Users"', "User's", 'User"s' ]
}

If you are looking for JSON output rather than JavaScript, mongosh also supports Extended JSON via the EJSON library:

EJSON.stringify(db.data.findOne())
{"_id":{"$oid":"634f8c8bef83f38d54a2a10e"},"thing":["Users","\"Users\"","User's","User\"s"]}

Regards,
Stennie

1 Like