Description
MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents.
MongoDB documents are composed of field-and-value pairs. The value of a field can be any of the BSON data types.
|
var mydoc = {
_id: ObjectId("5099803df3f4948bd2f98391"),
name: { first: "Alan", last: "Turing" },
birth: new Date('Jun 23, 1912'),
death: new Date('Jun 07, 1954'),
contribs: [ "Turing machine", "Turing test", "Turingery" ],
views : NumberLong(1250000)
}
|
Connect and authenticate
|
# connect
mongosh mongodb://localhost:27017
# alias
mongosh
# connect and authenticate, use an environment variable to hide the password
mongosh "mongodb://user:${DBPASSWORD}@<host>:<port>/admin?authSource=admin"
|
Authenticate
|
db.auth("username", "pwd")
db.auth("username", passwordPrompt())
|
Database
|
// list the databases
show dbs
// drop the current database
db.dropDatabase()
|
Backup and restore
|
# restore the backup folder dump to the local mongodb instance
mongorestore dump/
|
don't know what to do with file while restore
This may happen because the mongorestore command point to a backup sub-folder not to the backup folder itself.
|
// list the users of the current database
db.getUsers()
db.runCommand('usersInfo')
// get info of a specific user
db.getUser("tom", { showCredentials: true, showPrivileges: true, showAuthenticationRestrictions: true })
// create admin
use admin
db.createUser(
{
user: "admin",
pwd: "mypwd",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
// create a user for the demo database
use demo
db.createUser(
{
user: "tom",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "readWrite", db: "demo" },
{ role: "read", db: "finances" } ]
}
)
// change password
use admin
db.changeUserPassword("tom", "secretpassword")
db.changeUserPassword("tom", passwordPrompt())
// delete a user
db.dropUser("tom")
|
/etc/mongod.conf
|
security:
authorization: "enabled"
|
Bash
|
mongo <<EOF
use admin
db.auth("admin", "${MONGODBADMINPWD}")
use mydb
db.dropDatabase()
EOF
|
Compass
Windows
|
choco install mongodb mongodb-shell
|
Key
|
Value
|
Service name |
MongoDB
|
Data directory |
C:\Program Files\MongoDB\Server\6.0\data\
|
Log directory |
C:\Program Files\MongoDB\Server\6.0\log\
|
|
yay mongodb-bin
# install dependencies mongodb-bin-debug, mongosh-bin, mongosh-bin-debug
# GUI
yay mongodb-compass
# tools
yay mongodb-tools
# service
sc-status mongodb.service
|