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"})
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With