Note : For Mongo Cloud
- Set Password: Select Cluster > Security >Select User > Edit
- Add IP : Select Cluster > Security > Network Access > Add IP Address
ref:
SQL VS MongoDB
- Database = Database
- Tables = Collections
- Rows = Documents
- Install Docker
Steps:
-
Open Terminal
-
docker run -d -p 27017:27017 mongo docker ps -a docker exec -it <containerid> bash $mongosh
-
CRUD
// Comment use test db.createCollection("T") show tables //insert into T (sl,name,age) values (1,'Ram,10) db.T.insertMany([{sl: 1,name: "Ram",age: 10} , {sl: 2,name: "Sam",age: 8} ]) //update T set age=11 where name='Ram' db.T.updateMany({ name: 'Ram'},{ $set: { age: 11 } }); //delete from T where name ='Ram' db.T.deleteMany({ name: "Ram" })
-
Select
show tables// select * from T db.T.find() //select sl,name from posts //1 = show db.T.find({}, {sl: 1, name: 1 }) //select * from T where name='Ram' db.T.find({name: 'Ram'}) //select * from T where age>=3.5 db.T.find({age: {$gte: 11}}) db.T.find( {$and: [ { $or: [{age: {$lt : 10 }}, {sl : { $gt: 1 }} ]}, { $or: [{ age: 11 }, {sl : { $lt : 100 }} ]} ] })
compare values:
- $eq (equal): db.inventory.find( { quantity: { $ne: 20 } } )
- $ne (not equal)
- $gt (greater than )
- $gte (greater than or equal )
- $lt (less than)
- $lte (less than or equal )
- $in(matched within an array)
Logical
- $and: Returns documents where both queries match
- $or: Returns documents where either query matches
- $nor: Returns documents where both queries fail to match
- $not: Returns documents where the query does not match
Evaluation
- $regex: Allows the use of regular expressions when evaluating field values
- $text: Performs a text search
- $where: Uses a JavaScript expression to match documents
Update
- $currentDate: Sets the field value to the current date
- $inc: Increments the field value
- $rename: Renames the field
- $set: Sets the value of a field
- $unset: Removes the field from the document
Update Array
- $addToSet: Adds distinct elements to an array
- $pop: Removes the first or last element of an array
- $pull: Removes all elements from an array that match the query
- $push: Adds an element to an array
Python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client['test'] #Creates DB if not exists
if "C" not in db.list_collection_names():
db.create_collection("C")
db["C"].insert_one({"c":2,"d":3})
for i in db["C"].find():print(i)