MongoDB working notes: collections, JSON vs BSON, and CRUD operations with their shell commands.
1. Collections
show collections→ To list collectionsdb.customer.insertOne({"name":"Ram"})→ Implicit creationdb.createCollection("customers")→ Explicit Creationdb.createCollection(nameOfCollection, options)→ Syntax- options →
{capped: true}if true, need to give size. {size: 34234}in bytes{autoIndexId: true}If true,_idwill be indexed{max:100}max 100 docs in a collections for capped collectiondb.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
_idis not provided, mongoDb will give unique UUID. If specified, mongo will use that writeConcernoption →orderedoption →
b. Read
- Two ways
db.collection.find(filters, options),db.collection.findOne() findOnemethod gives the first match, and default sorting is based on insertion order, the first inserted will come firstfind→ if no filter given, it will return all docs, but in a cursor/iteratoroptions→ 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