MongoDB

Collection

MongoDB collection is analogically to table in MySQL.

 

MongoDB Collection Commands

 

1. create new collection in my_db database

> use my_db

> db.createCollection('users')

{ "ok" : 1 }

 

 

 

2. show collections in database

> show collections

poruke
system.indexes
users

 

3. drop collection (collection will no longer exist and > show collections will not list that collaection)

> db.poruke.drop()

true

 

4. insert document into collection

> db.users.insert({'user' : 'mrko'})

> db.users.insert({'user' : 'sasa'})

 

> db.users.insert({'user':'pero'},{'user':'mrko'})      -will insert just first document. Can't insert 2 docs at the same time.

 

 

5.  list documents

- all documents inside collection

> db.users.find()

{ "_id" : ObjectId("5527f06389f512f82c94ea60"), "user" : "pero" }
{ "_id" : ObjectId("5527f1bb89f512f82c94ea61"), "user" : "mrko" }

 

- documents by query

> db.users.find( {'user' : 'mrko'} )

{ "_id" : ObjectId("5527f1bb89f512f82c94ea61"), "user" : "mrko" }

 

 

 

 

6. Empty collection. Remove documents from collection so collection becomes empty.

> db.users.remove({'user':'pero'})      - remove specific document

> db.users.remove()        - remove all documents from collection

 

Notice that collection is still present (not deleted), e.g. > show collections will list 'users' collection.