Summary of examples of mongodb basic commands

  • 2020-12-13 19:10:27
  • OfStack

This article gives an example of the mongodb basic command. To share for your reference, the details are as follows:

1 Switch database


use admin;

View the current database


db;

2.1 View all databases


show dbs;

View the table below the current database


show collections;

4 Delete the database


use test;
db.dropDatabase(); # Delete the current database 
show dbs;  # Verify deletion results 

Delete a collection or table


db.table_name.drop(); # Delete table  table_name

6. Check account information


mongo --port=23000
use admin;
db.auth('username','password')
db.system.users.find().pretty()  # View all account information 
show users; # View the current account information 
db.getUser('username') # View information about the specified user 

7 Use gzip compression backup and restore, note that as long as the command is changed, the rest of the same, there is no user name and password set here


mongodump  --port=23000 --archive=/data/mongo_backup/testdb-2.20191203.gz --db testdb-2 --gzip
mongorestore --port=23000 --archive=/data/mongo_backup/testdb-2.20191203.gz --db testdb-2 --gzip
**  This backup is generated 1 a gzip File, also unzipped 1 Three files, put everything in there 1 In the file of 

Uncompressed backup mode


mongodump --port=23000 --db=testdb-2 -o /data/mongo_backup/20191203
mongorestore --port=23000 --db=testdb-2 --drop /data/mongo_backup/20191203/testdb-2
** With this backup, there are usually two files per table: .bson and .metadata.json

9 Query using the mongo command in shell


#  use eval mongo ip:port/database --eval ""
[root@localhost ~]# mongo localhost:23000/testdb-2 --eval "printjson(db.table1.findOne())"
MongoDB shell version v3.6.13
connecting to: mongodb://localhost:23000/testdb-2?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("e87ef5ae-a6b7-47d6-a91c-65f3a0b81ac0") }
MongoDB server version: 3.6.13
{
  "_id" : ObjectId("5de60a767321940034390f16"),
  "id" : 129,
  "name" : "hehe"
}
# use --quiet  Remove unnecessary information 
[root@localhost ~]# mongo localhost:23000/testdb-2 --quiet --eval "printjson(db.table2.findOne())"
{ "_id" : ObjectId("5de615b8eac07a724c6911b6"), "id" : 6, "name" : "hehe" }


db;

0

The mongo command is used in the 10 shell script


db;

1

db;

2

I hope that this article has been helpful to the MongoDB database programming.


Related articles: