1. Collections
show collections
→ To list collections
db.customer.insertOne({"name":"Ram"})
→ Implicit creation
db.createCollection("customers")
→ Explicit Creation
db.createCollection(nameOfCollection, options)
→ Syntax
- options →
{capped: true}
if true, need to give size.
{size: 34234}
in bytes
{autoIndexId: true}
If true, _id
will be indexed
{max:100}
max 100 docs in a collections for capped collection
db.customers.drop()
To drop/delete the collection
2. JSON vs BSON
3. CRUD - Operations
a. Create
- syntax →
db.customers.insertOne(jsonDocument,options)
This will insert one document in the collection.
db.customers.insertMany(ArrayOfJsonDocuments, options)
This will insert all the documents in the array
- If
_id
is not provided, mongoDb will give unique UUID. If specified, mongo will use that
writeConcern
option →
ordered
option →
b. Read
- Two ways
db.collection.find(filters, options)
, db.collection.findOne()
findOne
method gives the first match, and default sorting is based on insertion order, the first inserted will come first
find
→ if no filter given, it will return all docs, but in a cursor/iterator
options
→ the options can be an object to tell what keys are required. {name:true,_id:false}
c. Update
updateOne(filter, operatorWithValueTobeUpdated)
→ Updates first doc that passes the filter.
- Example -
db.collection.updateOne({name:"john"}, {$set: {name:"John", age:50}})
updateMany(filter, OperatorWithUpdateValue)
→ Updates all the docs which matches the filter
d.