MongoDB Mini User Guide

Shell Mongo :
> mongo

Once you are in terminal/command line, access the database/collection you want to use as follows:

show dbs
use <db name>
show collections

choose your collection and type the following to see all contents of that collection:

db.collectionName.find()

for a query below some samples :

db.products.find({ "_id": "apples", "qty": 5 }
db.products.find( { qty: { $gt: 25 } } )
db.students.find( { score: { $gt: 0, $lt: 2 } } )
db.bios.find( { _id: 5 } )
db.bios.find( { contribs: "UNIX" } ) >>>>>> Array elements

Check this link for more : https://docs.mongodb.com/manual/reference/method/db.collection.find/

Import / Export command in MongoDB (Unicode files)(json)

mongoimport -d comedy -c cartoons -file collections.json
mongoexport -d comedy -c cartoons -o collections.json

Change collection name in mongodb

db.oldname.renameCollection("newname")

Change type fields :

// String to Integer for notice_id
db.mycollection.find({notice_id : {$exists : true}}).forEach( function(obj) { obj.notice_id = new NumberInt(obj.notice_id); db.mycollection.save(obj); } );
// Integer to String for field-name
db.db-name.find({field-name : {$exists : true}}).forEach( function(obj) { obj.field-name = ""+obj.field-name; db.db-name.save(obj); } );

Rename a field in mongoDB :

db.mycollection.update ( {}, { $rename : { "notice_id" : "isn" }}, false, true );

Delete a collection

db.compta.drop();

Empty a collection

db.compta.remove();

Under the Mongodb shell please import the follwing json file (test.json) listed below with :

mongoimport -d test -c compta -file d:test.json

{ “montant” : 3.95, “travel” : “Prague”, “sens” : “credit” }
{ “montant” : 6.03, “travel” : “Prague”, “sens” : “credit” }
{ “montant” : 5.53, “travel” : “New York”, “sens” : “credit” }
{ “montant” : -1.96, “travel” : “New York”, “sens” : “debit” }
{ “montant” : 3.95, “tickets” : “eurodisney”, “sens” : “credit” }
{ “montant” : 6.03, “tickets” : “asterix”, “sens” : “credit” }

Mongo Request Sum or Total aggregate :

db.compta.aggregate({$group:{
_id:"",
montant: {$sum: "$montant"}}
}, {$project:{
_id:0,
montant: "$montant"}});

db.compta.aggregate({$group:{
_id:"$travel",
montant: {$sum: "$montant"}}
}, {$project:{
_id:1,
montant: "$montant"}});

<br?>

extradrmtech

Since 30 years I work on Database Architecture and data migration protocols. I am also a consultant in Web content management solutions and medias protecting solutions. I am experienced web-developer with over 10 years developing PHP/MySQL, C#, VB.Net applications ranging from simple web sites to extensive web-based business applications. Besides my work, I like to work freelance only on some wordpress projects because it is relaxing and delightful CMS for me. When not working, I like to dance salsa and swing and to have fun with my little family.

You may also like...