Top 10 Frequently Used queries in Mongo Database with example
This tutorials explains about frequently used queries in MongoDB
How to select database in Mongodb
admin>
admin>use moviesdb;
switched to db moviesdb
moviesdb>
MongoDB List All Collections command
For command line,Below commands list out all collections of a database.
- show collections
- show tables
- db.getCollectionNames()
The above command works in non-scripted and command line works in Mongo Shell Terminal
moviesdb>show collections
comments
movies
sessions
theaters
users
or
moviesdb>show tables
comments
movies
sessions
theaters
users
db.getCollectionNames()
returns an array of collection names. It works as command line as well as in code script.
You can use this in Code API from an application
db.getCollectionNames()
[ 'comments', 'users', 'sessions', 'theaters', 'movies' ]
Mongo List all Databases command
show dbs
or show database
command in shell list out all commands.
show dbs;
admin 40.00 KiB
config 112.00 KiB
ecommerce 8.00 KiB
local 40.00 KiB
moviesdb 28.46 MiB
Print list of users in Mongo Shell
show users
: return an array of users in Mongodb
show users;
["admin"]
Print list of roles in Mongo Shell
show roles
: return an array of roles object in Mongodb. Roles object contains role assigned to database and inheritedRoles.
show users;
[
inheritedRoles: []
},
{
role: 'readWrite',
db: 'moviesdb',
isBuiltin: true,
roles: [],
inheritedRoles: []
},
{
role: 'userAdmin',
db: 'moviesdb',
isBuiltin: true,
roles: [],
inheritedRoles: []
},
{
role: 'dbOwner',
db: 'moviesdb',
isBuiltin: true,
roles: [],
inheritedRoles: []
},
{
role: 'enableSharding',
db: 'moviesdb',
isBuiltin: true,
roles: [],
inheritedRoles: []
},
{
role: 'dbAdmin',
db: 'moviesdb',
isBuiltin: true,
roles: [],
inheritedRoles: []
}
]
moviesdb>
Count of documents in a collection in mongo Shell
countDocuments()
: returns number records in a collection
db.users.countDocuments();
185
List of indexes for an collection in Mongodb
db.collection.getIndexes() returns the indexes for a given collection in a Database.
db.user.getIndexes()
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]