Few Tips for MongoDB

2014/05/022 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Update All Fields
  3. Between Statement
  4. Like Statement
  5. Not In Statement
  6. Not In with Multiple Values
  7. Check the Database Size
  8. Drop Database in Command
  9. Drop Collection in Command
  10. Remote MongoLab
  11. MongoDB Aggregate Example
  12. Conclusion

Introduction

This post contains a few MongoDB script and command notes for common database operations. These quick references cover updates, queries, database management, and aggregation.

Update All Fields

db.SomeMongoDBTable.update(
  // query
  { "TableFiledQuery" : true },
  // update
  { $set : {'FiledWantToChange': false} },
  // options
  {
    "multi" : true,       // update all matching documents
    "upsert" : false      // do not insert a new document if no match
  }
);

Between Statement

Search for documents where the Id is greater than 5 and less than 10:

{ "Id" : {$gt: 5, $lt: 10}}

Like Statement

Search the Name field for documents containing a "like" string:

{ "Name" : {$regex: 'like'}}

Not In Statement

Find documents where Key (string) is not equal to "not this value":

{ "Key" : { $ne : "not this value"}}

Not In with Multiple Values

Return data where the Key field is not equal to victoria, los-angeles, or las-vegas:

{ "Key" : {$nin: ['victoria','los-angeles','las-vegas']}}

Check the Database Size

> show dbs dataSize

Drop Database in Command

Simply run the following command:

use {your database}
db.dropDatabase();

Drop Collection in Command

Simply run the following command:

db.{your collection name}.drop()

Remote MongoLab

Simply run the following command to connect:

>mongo {hostname}:{portnumber}/{database name} -u {user name} -p {password}

MongoDB Aggregate Example

db.Collection.aggregate(
[
{
	$match : {"State" : "CA"}
},
{
$group:
{
_id: null,
total: { $sum: "$TotalAmout" }
}
}
]
)

This is similar to the following SQL:

SELECT SUM(TotalAmount) AS total
FROM Collection
WHERE State = 'CA'

Conclusion

MongoDB syntax is different from traditional relational databases like MS SQL Server and Oracle. It takes time to get familiar with these commands. The examples above cover the most common operations you'll need when working with MongoDB.

Reference