Few Tips for MongoDB
Table of Contents
- Introduction
- Update All Fields
- Between Statement
- Like Statement
- Not In Statement
- Not In with Multiple Values
- Check the Database Size
- Drop Database in Command
- Drop Collection in Command
- Remote MongoLab
- MongoDB Aggregate Example
- 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.