CURD basic operation of MongoDB

Note: This paper is based on MongoDB 4.2.6

1. Delete

  • Delete a document
> db.bb.find().pretty()
{
	"_id" : ObjectId("5ed6549830571733ccb3d678"),
	"jordan" : 23,
	"haha" : "ending"
}
{
	"_id" : ObjectId("5ed6549830571733ccb3d679"),
	"kobe" : 24,
	"haha" : "ending"
}
> db.bb.remove({jordan: 23})
WriteResult({ "nRemoved" : 1 })
> db.bb.find().pretty()
{
	"_id" : ObjectId("5ed6549830571733ccb3d679"),
	"kobe" : 24,
	"haha" : "ending"
}

To delete a document, you need to match it first. For matching rules, it is consistent with update() and find().

However, it should be noted that remove() will delete all matching documents,

> db.bb.find().pretty()
{
	"_id" : ObjectId("5ed6549830571733ccb3d679"),
	"kobe" : 24,
	"haha" : "ending"
}
{
	"_id" : ObjectId("5ed6549830571733ccb3d67a"),
	"tmac" : 1,
	"haha" : "ending"
}
{
	"_id" : ObjectId("5ed6554230571733ccb3d67b"),
	"name" : "jay",
	"hello" : "ball",
}
> db.bb.remove({"haha" : "ending"})
WriteResult({ "nRemoved" : 2 })
> db.bb.find().pretty()
{
	"_id" : ObjectId("5ed6554230571733ccb3d67b"),
	"name" : "jay",
	"hello" : "ball"
}
  • Delete collection all documents
> db.aa.find().pretty()
{ "_id" : ObjectId("5ed7b329582b5fea09b920a6"), "name" : "aa", "id" : 100 }
{ "_id" : ObjectId("5ed7b351582b5fea09b920a7"), "name" : "bb", "id" : 101 }
> db.aa.remove()
2020-06-03T10:30:01.574-0400 E  QUERY    [js] uncaught exception: Error: remove needs a query :
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:357:15
DBCollection.prototype.remove@src/mongo/shell/collection.js:384:18
@(shell):1:1
> db.aa.remove({})
WriteResult({ "nRemoved" : 2 })
> db.aa.find().pretty()
> show collections
aa

Note that when remove() deletes all documents, it needs to add a query statement, that is, {}, otherwise an error will be reported. In addition, remove() does not delete the collection itself.

  • Delete collection

If you need to delete the collection together, you can use drop()

> db.aa.find().pretty()
{ "_id" : ObjectId("5ed7b4f5582b5fea09b920ac"), "name" : "aa", "id" : 100 }
{ "_id" : ObjectId("5ed7b4f8582b5fea09b920ad"), "name" : "bb", "id" : 101 }
> db.aa.drop()
true
> show collections
>
  • Delete database
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

2. Backup

  • Catalog backup
    Use the cp or rsync command to copy the MongoDB data directory directly. However, you need to stop all MongoDB instances before copying. Otherwise, if the copied files are still written, the backed up data will become inconsistent.
    Of course, you can not stop the instance, but you need to brush the cache and prohibit writing. At this time, you can ensure the normal reading operation. You can use the following command to lock the database,
> db.fsyncLock()
{
	"info" : "now locked against writes, use db.fsyncUnlock() to unlock",
	"lockCount" : NumberLong(1),
	"seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
	"ok" : 1
}

After the backup, use the following command to unlock,

> db.fsyncUnlock()
{ "info" : "fsyncUnlock completed", "lockCount" : NumberLong(0), "ok" : 1 }
  • mongodump command backup
mongodump -d dbname -u username -p password --authenticationDatabase admin --host="mongodb-ip:27017" -o /home/data/mydb_$(date +%Y%m%d)

Among them,
-d specify database name
-u specify user name
-p specify password
– authenticationDatabase specifies the database to connect to for authentication
– host specifies the database ip and port number
-o specify backup file storage path

After execution, you can view the backup information in the corresponding directory,

[root@localhost data]# mongodump -d abc -u root -p root --authenticationDatabase admin --host="localhost:27017" -o /home/mongodb/data/db_$(date +%Y%m%d)
2020-06-20T23:32:59.930-0400	writing abc.bb to 
2020-06-20T23:32:59.931-0400	done dumping abc.bb (2 documents)
[root@localhost data]# ls
db_20200620
[root@localhost data]# cd db_20200620/
[root@localhost db_20200620]# ls
abc
[root@localhost db_20200620]# cd abc/
[root@localhost abc]# ls
bb.bson  bb.metadata.json

For the files out of dump, we can use bsondump to view them,

[root@localhost abc]# bsondump bb.bson 
{"_id":{"$oid":"5ed6554230571733ccb3d67b"},"name":"jay","hello":"ball","animals":{"dog":{"$numberDouble":"50.0"},"cat":{"$numberDouble":"100.0"}},"happy":"ending","players":[{"name":"aa","score":{"$numberDouble":"98.0"}},{"name":"dan","score":{"$numberDouble":"95.0"}},{"name":"du","score":{"$numberDouble":"100.0"}}]}
{"_id":{"$oid":"5ed6579b30571733ccb3d67c"},"name":"jack","hello":"may","happy":"ending","players":[{"name":"aa","score":{"$numberDouble":"99.0"}},{"name":"dan","score":{"$numberDouble":"98.0"}},{"name":"du","score":{"$numberDouble":"90.0"}}]}
2020-06-20T23:44:27.676-0400	2 objects found

There is also a problem involved in backup, which takes time. Therefore, it is necessary to consider how to deal with the data modification during backup. If you are not careful, the data will be inconsistent. You can use< --Oplog > parameter, but it will save all operations of the database from the beginning to the end of the backup, and then replay the operations when restoring the backup to ensure the consistency of the data.

3. Recovery

After backup, we delete the collection of the database and simulate exceptions,

> db
abc
> show collections
bb
> db.bb.drop()
true
>

Then use the data just backed up for recovery, and use the mongorestore command,

[root@localhost data]# mongorestore --host=localhost:27017 -u root  --authenticationDatabase=admin /home/mongodb/data/db_20200620
Enter password:

2020-06-20T23:56:38.747-0400	preparing collections to restore from
2020-06-20T23:56:38.747-0400	reading metadata for abc.bb from /home/mongodb/data/db_20200620/abc/bb.metadata.json
2020-06-20T23:56:38.754-0400	restoring abc.bb from /home/mongodb/data/db_20200620/abc/bb.bson
2020-06-20T23:56:38.757-0400	no indexes to restore
2020-06-20T23:56:38.757-0400	finished restoring abc.bb (2 documents, 0 failures)
2020-06-20T23:56:38.757-0400	2 document(s) restored successfully. 0 document(s) failed to restore.

After the recovery, check the data in the database to confirm the integrity,

> show collections
bb
> db.bb.find()
{ "_id" : ObjectId("5ed6554230571733ccb3d67b"), "name" : "jay", "hello" : "ball", "animals" : { "dog" : 50, "cat" : 100 }, "happy" : "ending", "players" : [ { "name" : "aa", "score" : 98 }, { "name" : "dan", "score" : 95 }, { "name" : "du", "score" : 100 } ] }
{ "_id" : ObjectId("5ed6579b30571733ccb3d67c"), "name" : "jack", "hello" : "may", "happy" : "ending", "players" : [ { "name" : "aa", "score" : 99 }, { "name" : "dan", "score" : 98 }, { "name" : "du", "score" : 90 } ] }
> 

Of course, if the < -- oplog > parameter is used for backup, the < -- oplogreplay > parameter is needed for recovery and playback operation.

Keywords: MongoDB Database shell JSON

Added by StefanRSA on Sun, 21 Jun 2020 09:46:27 +0300