Few Tips for MongoDB

2014/5/22 min read
bookmark this
Responsive image

Just few mongo db script/command note

 

Update All Fileds

db.SomeMongoDBTable.update(

//query

{ "TableFiledQuery" : true },

//update

{ $set : {'FiledWantToChange': false} },

// options

{

"multi" : true,// update only one document

"upsert" : false // insert a new document, if no existing document match the query

} );

Between statement -search the Id greater than 5 and less than 10 


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

 

Like Statement -search Name field's contains %like% string 


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

 

Not in statement - Key(string) is not "not this value"


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

 

Check the database size

> show dbs dataSize 

Not in, following example

return data where Key field is not equal to victoria,los-angeles,las-vegas.


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

Drop database in command

Simply just run following command

use {your dabase}
b.dropDatabase();

Drop collection in command

Simply just run following command

db.{your collection name}.drop()
 

Remote MongoLab

Simply just run following command, that it.

>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" }
         }
     }
   ]
)

Similar to

SELECT (TotalAmount) AS total
       FROM Collection
       GROUP BY TotalAmout
       HAVING State = 'CA'

conclusion

Mongo DB syntax is different from existing relational database like MS SQL SERVER, Oracle. It take time to get familiar with these. My next plan is write compare sql between existing relational database script syntax and compare with Mongo DB.

Reference

http://cookbook.mongodb.org/patterns/date_range/

http://docs.mongodb.org/manual/reference/command/nav-diagnostic/