Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB the difference between db.getCollection.find and db.tablename.find?

What is the difference between:

db.getCollection('booking').find()

and

db.booking.find()

Are they exactly the same, or when should I use which one?

db.getCollection('booking').find({_id:"0J0DR"})

db.booking.find({_id:"0J0DR"})
like image 521
torbenrudgaard Avatar asked Apr 04 '17 14:04

torbenrudgaard


2 Answers

Yes, they are exactly the same and you can use either.

The first form db.getCollection(collectionName).find() becomes handy when your collection name contains special characters that will otherwise render the other syntax redundant.

Example: Suppose your collection has a name that begin with _ or matches a database shell method or has a space, then you can use db.getCollection("booking trips").find() or db["booking trips"].find() where doing db.booking trips.find() is impossible.

like image 171
chridam Avatar answered Sep 28 '22 02:09

chridam


I prefer using db.collection() to either as it will work on nonexistent collections, which is particularly useful when for example creating the first user in a users collection that doesn't yet exist.

db.collection('users').findOneAndUpdate(...) // Won't throw even if the collection doesn't exist yet
like image 26
Dominic Avatar answered Sep 28 '22 02:09

Dominic