MongoDB

MongoDB

aahoo

`mongod --directoryperdb --dbpath c:\mdb\data\db --logpath c:\mdb\log\mdb.log --logappend --rest --install`

`show dbs`

`use <db-name>` e.g `use mycustomers` : (creates and )switches to the db

`db` shows the current db

db.createUser({ user: "test",
pwd: "testingpassword",
roles: [ "readWrite", "dbAdmin" ]
})

`db.createCollection('customer');`

`show collections`

`db.customer.drop()` removes the entire collection

`db.customers.insert({first_name: "John" , last_name: "Doe"});`

`db.customers.insert([{}, {}]);` for batch insert

`db.customers.find();` shows entries in a collection

`db.customers.find().pretty();`

`db.customers.update(<match object>, <replace with>);`

`db.customers.update({first_name: "John"}, {first_name:"John", last_name: "Doe", gender: "male"});`

`db.customers.update({first_name:"John"},{$set:{age:45}});`

`db.customers.update({first_name:"John"},{$inc:{age:5}});`

`db.customers.update({first_name:"John"},{$unset:{age:1}});` removes the age property

`db.customers.update({first_name: "New Name"}, {first_name:"New Name", last_name: "New Last Name"}, {upsert: true});` insert if no match

`db.customers.update({first_name: "John"}, {$rename:{"gender": "sex"}});`

`db.customers.remove({first_name: "Will"}, {justOne: true});` deletes only the first one

`db.customers.remove({$and: [{first_name: "Will"}, {gender: {$ne: "male"}}]});`

`db.customers.update({first_name: "ham"},{$set: {address: {city: "Solna", street: "Kungshamra"}}});`

`db.customers.find({"address.city": "Solna"})` object property name should be in double quotes

`db.customers.find().sort({last_name:1}).pretty();` 1 sorts ascending, -1 sorts descending

`db.customers.find().count();`

`db.customers.find().sort({last_name:1}).limit(2).pretty();`

`db.customers.find().forEach(function(doc){print("First Name: ", doc.first_name)});`

Report Page