Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Repair and compact database in MongoDB

Answer:

To repair and compact a database in MongoDB, you can use the following command in the mongodb Interactive shell.

1. Select the database

use test

2. Repair the current database

db.repairDatabase()

Done.

Count the total number of objects in the collection in MongoDB

Answer:

In MongoDB, to count the total number of objects in the collection, you can use the following statement in the mongodb Interactive shell.

db.test.count()

The above statement will return the total number of objects in the collection "test"

Creates an index in MongoDB

Answer:

In an given collection, if you want to add an index on a specify field, you can do the following in the mongodb Interactive shell.

db.test.ensureIndex( { name : 1 } )

The key "name" from now on will have index enabled.

Show the storage used by a database in MySQL

Answer:

In previous article, we have already discussed how to list the database size in your MySQL server.

But if you want to have a more detail view on an individual database, you can try the following (crazy) SQL.

SELECT s.schema_name,
CONCAT(IFNULL(ROUND((SUM(t.data_length)+SUM(t.index_length))
/1024/1024,2),0.00),"Mb") total_size,
CONCAT(IFNULL(ROUND(((SUM(t.data_length)+SUM(t.index_length))-SUM(t.data_free))/1024/1024,2),0.00),"Mb")

data_used,
CONCAT(IFNULL(ROUND(SUM(data_free)/1024/1024,2),0.00),"Mb") data_free,
IFNULL(ROUND((((SUM(t.data_length)+SUM(t.index_length))-SUM(t.data_free))
/((SUM(t.data_length)+SUM(t.index_length)))*100),2),0) pct_used,
COUNT(table_name) total_tables
FROM INFORMATION_SCHEMA.SCHEMATA s
LEFT JOIN INFORMATION_SCHEMA.TABLES t ON s.schema_name = t.table_schema
WHERE s.schema_name = "mydatabase"
GROUP BY s.schema_name
ORDER BY pct_used DESC\G

It will give you something like the following..

 schema_name: mydatabase
  total_size: 165.09Mb
   data_used: 12.09Mb
   data_free: 153.00Mb
    pct_used: 7.33
total_tables: 133

Update an existing document in MongoDB

Answer:

In an given collection, if you want to perform update on an existing document, the easiest way is to use the following commands.

employee = db.employees.findOne( { name : "Peter" } );
employee.position = "Project Manager";
db.employees.save( employee );

Done.