MongoDB

Update a record from cli

Theory db.users.update({QUERY},{UPDATE}) Example db.users.update({"username":"sij"},{$set:{"role":"changer"}})

Search mongo document and exclude data

db.users.find({"status":{$not:{$eq:"closed"}}})

Search documents with a missing field

db.articles.find({"article_id":{$exists: false}}) db.articles.find({"article_id":{$exists: false}}).count() Searching documents with an explicit field db.articles.find({"article_id":{$exists: true}}) db.articles.find({"article_id":{$exists: true}}).count() Source https://docs.mongodb.com/man...

MongoDB Cheatsheet

Connect from the local shell mongo Show all dbs show dbs Connect with a db use DB-NAME Show currently connected db db Show all collections show collections Show all entries of a collection db.COLLECTION-NAME.find({}) Show all entries of a collection PRETTY db.COLLECTION-NAM...

Drop database

Display all databases > show dbs admin 0.000GB config 0.000GB local 0.000GB onews 0.001GB Connect with the db to delete use onews Delete the db db.dropDatabase() Verify the result > show dbs admin 0.000GB config 0.000GB local 0.000GB

Create for every document in the collection a new field

db.articles.update({}, {$set:{"categories":[]}},{"multi":true}) Source https://docs.mongodb.com/manual/reference/method/db.collection.update/

Backup/restore a database

Backup the database mongodump --db=database-name Creates a directory “dump”, which contains a folder with the db name. And this director contains the backup files of all collections. With “–out=” you can specify where you want the backup to be stored. Restore the database mongorestore --db=d...

Backup, delete and restore collections

Backup the collection mongodump --collection=collection-name --db=database-name Creates a directory “dump”, which contains a folder with the db name. And this director contains the backup files of the collection. With “–out=” you can specify where you want the backup to be stored. Delete the c...