# pymongo :

pymongo পাইথন প্যাকেজ ইনস্টল থাকতে হবে।&#x20;

```bash
pip install pymongo
```

আমার কাজের সুবিধার জন্য আমি এখানে জুপিটার নোটবুক ব্যবহার করছি অন্য এডিটরেও কাজ করা যাবে।

### প্রথমে pymongo লাইব্রেরি ইম্পোর্ট করি

```python
import pymongo
```

MongoClint সেট করে মঙ্গো সার্ভার এর সাথে কানেক্ট করি

```python
myclint = pymongo.MongoClient('mongodb://localhost:27017/')
```

### ডাটাবেজ একসেস করি:

&#x20;যদি আগে থেকে ডাটাবেজ না থাকে তাহলে ডাটাবেজ তৈরী হবে। তবে এক্ষেত্রে শর্ত হলো যতক্ষণ পর্যন্ত কোন ডেটা ডেটাবেজ এ ইন্সার্ট করবো। ডেটা ছাড়া মঙ্গো ডাটাবেজ তৈরী করবে না

```python
mydb = myclint['test']
```

**ডেটাবেজ দেখা :**&#x20;

আগে থেকে যে ডেটাবেজ তৈরী করা আছে তা দেখতে নিচের কোড রান করি।

<pre class="language-python"><code class="lang-python"><strong>print(myclint.list_database_names())
</strong>Output:
['admin', 'config', 'local', 'school', 'test']
</code></pre>

**কালেকশন বা টেবিল তৈরী /এক্সেস করি**

ডেটাবেজ এ একটি কালেকশন বা টেবিল তৈরী /এক্সেস করি :

তবে এক্ষেত্রে শর্ত হলো যতক্ষণ পর্যন্ত কোন ডেটা ডেটাবেজ এ ইন্সার্ট করবো। ডেটা ছাড়া মঙ্গো কালেকশন বা টেবিল তৈরী করবে না

```python
mycol = mydb['customers']
```

#### ডেটা ইন্সার্ট করা

```python
mydict = {"name":"gsm ashik","roll":17}
x = mycol.insert_one(mydict)
print(x.inserted_id)
#output 6464e214b13a301bf8a8ce7c (last inserted id generated by mongodb)
```

**একাধিক রও ইন্সার্ট করা**

```python
mylist = [
    {
        "name":"Mim","roll":6
    },
    {
       "name":"Mahmuda","roll":7
    }
]
y= mycol.insert_many(mylist)
```

### Mongodb কোয়েরি :&#x20;

সিঙ্গেল একটি সারি রিটার্ন করা

```python
x = mycol.find_one()
 
print(x)
```

**সব গুলো ডেটা দেখা**

```python
for x in mycol.find():
    print(x)
    
#output
'''{'_id': ObjectId('646445eb5baf1ceb41201f0a'), 'name': 'olee ahmmed ashik', 'roll': 25}
{'_id': ObjectId('646451bb5baf1ceb41201f0d'), 'name': 'trek', 'roll': 25}
{'_id': ObjectId('646452155baf1ceb41201f0f'), 'name': 'fokrul', 'roll': 14}
{'_id': ObjectId('6464e214b13a301bf8a8ce7c'), 'name': 'gsm ashik', 'roll': 17}
{'_id': ObjectId('6464e49fb13a301bf8a8ce7d'), 'name': 'Mim', 'roll': 6}
{'_id': ObjectId('6464e49fb13a301bf8a8ce7e'), 'name': 'Mahmuda', 'roll': 7}'''
```

**নির্দিষ্ট কলাম প্রিন্ট করা**

```python
cursor = mycol.find()
for result in cursor:
    print(result['name'])
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FhkurliESFN0XEo4rLbFd%2Fimage.png?alt=media&#x26;token=7b80d8d8-06be-4290-8642-20e0de18a157" alt=""><figcaption></figcaption></figure>

**LIMIT**&#x20;

```python
x = mycol.find().limit(5)
for result in x:
    print(result)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2F3rxB5oVSEKse41g4Wv2e%2Fimage.png?alt=media&#x26;token=ff011863-fb70-456a-9281-81579786581c" alt=""><figcaption></figcaption></figure>

**sort**

```python
cursor = mycol.find().sort([('roll',1)])
for result in cursor:
    print(f"Name: {result['name']}, Roll: {result['roll']}")
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2Fr9gI2vqlfYgnvyzFFw6h%2Fimage.png?alt=media&#x26;token=f1a42392-1f27-4cfe-aa15-d92a495f1e02" alt=""><figcaption></figcaption></figure>

**ফিল্টার করা :**&#x20;

ফিল্টার করে কোয়েরি করার জন্য কয়েকটি কীওয়ার্ড ব্যবহার করা হয়।

| Operation             | Syntax                                   | Description                                                                                             |
| --------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Equality              | {“key” : “value”}                        | Matches values that are equal to a specified value.                                                     |
| Less Than             | {“key” :{$lt:”value”}}                   | Matches values that are less than a specified value.                                                    |
| Greater Than          | {“key” :{$gt:”value”}}                   | Matches values that are greater than a specified value.                                                 |
| Less Than Equal to    | {“key” :{$lte:”value”}}                  | Matches values that are less than or equal to a specified value.                                        |
| Greater Than Equal to | {“key” :{$gte:”value”}}                  | Matches values that are greater than or equal to a specified value.                                     |
| Not Equal to          | {“key”:{$ne: “value”}}                   | Matches all values that are not equal to a specified value.                                             |
| Logical AND           | { “$and”:\[{exp1}, {exp2}, …, {expN}] }  | Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. |
| Logical OR            | { “$or”:\[{exp1}, {\<exp2}, …, {expN}] } | Joins query clauses with a logical OR returns all documents that match the conditions of either clause. |
| Logical NOT           | { “$not”:\[{exp1}, {exp2}, …, {expN}] }  | Inverts the effect of a query expression and returns documents that do not match the query expression.  |

**Equality :**

```python
cursor = mycol.find({"name":"trek"})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FGisJUF6XrF1M7C1gyrft%2Fimage.png?alt=media&#x26;token=9ef7af72-76ff-416d-85f2-605c8f7f1114" alt=""><figcaption></figcaption></figure>

**Not Equal To**

```python
# Not Equal To
cursor = mycol.find({'name':{"$ne":"Mim"}})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FzZ18jJGkkAqlozdRNsJG%2Fimage.png?alt=media&#x26;token=70caa47d-4627-4a32-992b-b264a7b3aada" alt=""><figcaption></figcaption></figure>

**Less Than**

```python
# Less Than
cursor = mycol.find({"roll":{'$lt':25}})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FMCQKlBOM8UUekTRAbzAt%2Fimage.png?alt=media&#x26;token=8c2918b6-c57c-40af-aa52-71678a633fed" alt=""><figcaption></figcaption></figure>

**Greater Than**

```python
# Greater Than
cursor = mycol.find({"roll":{"$gt":20}})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FenY1IV4oetNqxPWQvpZO%2Fimage.png?alt=media&#x26;token=12d48217-e312-4734-9d23-568b03818a95" alt=""><figcaption></figcaption></figure>

**IN**

```python
cursor = mycol.find({'name': {'$in': ['Mim', 'Mahmuda']}})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FGmbZaGNFx34pfHZZzKSp%2Fimage.png?alt=media&#x26;token=aa760e66-33be-43c5-ae0f-9c77c794fc31" alt=""><figcaption></figcaption></figure>

**AND**

```python
cursor = mycol.find({'$and': [{'name': 'Mim'}, {'roll': 6}]})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FR2Fc0RBJzAEYUB113O8x%2Fimage.png?alt=media&#x26;token=8b915c7a-1511-4d7c-a09f-f18705e5b263" alt=""><figcaption></figcaption></figure>

**OR**

```python
cursor = mycol.find({'$or': [{'name': 'Mim'}, {'roll': 7}]})
for record in cursor:
    print(record)
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FlqD6Hz94mgtP1KPxHmpT%2Fimage.png?alt=media&#x26;token=c3286c6a-63cb-41ac-bb99-989505b715d0" alt=""><figcaption></figcaption></figure>

**আপডেট রও :**

```python
import pymongo

myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['test']
mycol = mydb['customers']

# Define the filter criteria to identify the document to update
filter = {'name': 'olee', 'roll': 7}

# Define the new values to update in the document
new_values = {'$set': {'age': 25, 'city': 'New York'}}

# Update the document
mycol.update_one(filter, new_values)

print("Document updated successfully.")

```

**ডিলেট রো :**

```python
import pymongo

myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['test']
mycol = mydb['customers']


# Define the filter criteria
filter = {'name': 'olee ahmmed ashik', 'roll': 25}

# Delete the document
mycol.delete_one(filter)

print("Document deleted successfully.")
```

<figure><img src="https://2401964015-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FAvzwAkIYr9ffgOuW5T9W%2Fuploads%2FURsH6yS1cwO6AAKThlXi%2Fimage.png?alt=media&#x26;token=a8ca0a33-97d8-48d4-97b9-71ca74173507" alt=""><figcaption></figcaption></figure>

**ডিলেট ডকুমেন্ট :**

```
import pymongo

myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['test']
mycol = mydb['customers']

# Delete all documents in the collection
mycol.delete_many({})

print("All documents deleted successfully.")

```
