MongoDB is a NoSQL, 10gen Database system. Its scalability and high performance earning rapid popularity growth.

Lets see some basic shell commands of MongoDB.

1. Command to Create:

db.makewebsmart.insert({
  first: 'matthew',
  last: 'setter',
  dob: '21/04/1978',
  gender: 'm',
  hair_colour: 'brown',
  occupation: 'developer',
  nationality: 'australian'
});

few more examples:

 db.collection.insert( <document> )
 db.collection.save( <document> )
 db.collection.update( <query>,
    <update>,
    { upsert: true }
  );

2. Command to Select:

db.collection.find();
db.collection.find({gender: 'f'});
db.collection.find({gender: 'm', $or: [{nationality: 'english'}]});
db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]});

db.collection.findOne( <query>, <projection> )
db.collection.findOne();

 

example:

db.collection.findOne(
{
  $or: [
    { 'name.first' : /^G/ },
    { birth: { $lt: new Date('01/01/1945') } }
   ]
});

3. Sorting:

values:
Ascending: -1
Descending: 1

db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1});

another one example:

db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1, first: 1});

4. Limit:

db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2);

Skip 2:

db.collection.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2).skip(2);

5. Update:

db.collection.update({first: 'james', last: 'caan'}, {$set: {hair_colour: 'brown'}});

db.collection.update( <query>, <update>, <options> )

db.collection.save( <document> )
---
# db.collection.save(
{
  name: { first: 'Larry', last: 'Wall' },
  contribs: [ 'Perl' ]
});
---
# db.collection.update( <query>, <update>, <options> );

---
db.collection.update(
  { _id: 1 },
  {
    $set: { 'name.middle': 'Warner' },
    $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } }
  });
db.collection.update(
  { _id: 3 },
  { $unset: { birth: 1 } }
  );
db.collection.update(
  { _id: 3 },
  { $set: {
      mbranch: 'Navy',
      'name.aka': 'Amazing Grace'
    }
  }
)

6. Delete:

db.collection.remove({first: 'james', last: 'caan'});

To delete all the records from the database?

db.collection.remove();

7. Some more:

db.collection.findAndModify();

 

Here I have tried to show some basic commands. Visit MongoDB manual for elaborate guideline.

Comments

comments