0% found this document useful (0 votes)
2 views8 pages

NoSql

The document provides essential MongoDB commands for creating databases, collections, and performing CRUD operations. It also includes instructions for setting up a Flask application with PyMongo to handle RESTful requests for managing restaurant data. Additionally, it covers advanced querying techniques and dynamic filters for retrieving restaurant information.

Uploaded by

Amine Benjloun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

NoSql

The document provides essential MongoDB commands for creating databases, collections, and performing CRUD operations. It also includes instructions for setting up a Flask application with PyMongo to handle RESTful requests for managing restaurant data. Additionally, it covers advanced querying techniques and dynamic filters for retrieving restaurant information.

Uploaded by

Amine Benjloun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

Requêtes MongoDB essentielles


Créer Une Base :

Use Db

Créer Une Collection (Table) :

Db.CreateCollection("restauranats");

Insertion d'un document

db.restaurants.insertOne({
"name": "Le Gourmet",
"borough": "Paris",
"cuisine": "French",
"address": {
"street": "10 Rue de Rivoli",
"zipcode": "75001"
},
"grades": [
{ "date": ISODate("2023-01-01T00:00:00Z"), "grade": "A", "score": 18 }
]
});

Insertion multiple

db.restaurants.insertMany([
{
"name": "Pizza Napoli",

Untitled 1
"borough": "Naples",
"cuisine": "Italian",
"address": { "street": "Piazza Garibaldi", "zipcode": "80142" },
"grades": [{ "date": ISODate("2023-02-01T00:00:00Z"), "grade": "B", "sc
ore": 15 }]
},
{
"name": "Sushi Tokyo",
"borough": "Tokyo",
"cuisine": "Japanese",
"address": { "street": "Shibuya", "zipcode": "150-0002" },
"grades": [{ "date": ISODate("2023-03-01T00:00:00Z"), "grade": "A", "sc
ore": 20 }]
}
]);

Récupération d'un document

db.restaurants.findOne({ "name": "Le Gourmet" });

Récupération de tous les documents

db.restaurants.find({});

Requêtes avec filtres

db.restaurants.find({ "borough": "Brooklyn" });


db.restaurants.find({ "cuisine": "Italian" });
db.restaurants.find({ "grades.score": { "$gt": 15 } });

Untitled 2
Requête avec plusieurs critères

db.restaurants.find({ "borough": "Brooklyn", "cuisine": "Italian" });

Projection (sélectionner des champs spécifiques)

db.restaurants.find({ "borough": "Brooklyn" }, { "name": 1, "cuisine": 1, "_id": 0


});

Requête avec tri

db.restaurants.find().sort({ "name": 1 }); // Tri alphabétique ascendant


db.restaurants.find().sort({ "grades.score": -1 }); // Tri par score décroissant

Mise à jour d'un document

db.restaurants.updateOne(
{ "name": "Le Gourmet" },
{ "$set": { "cuisine": "Modern French" } }
);

Mise à jour de plusieurs documents

db.restaurants.updateMany(
{ "cuisine": "Italian" },
{ "$set": { "cuisine": "Authentic Italian" } }
);

Suppression d'un document

Untitled 3
db.restaurants.deleteOne({ "name": "Le Gourmet" });

Suppression de plusieurs documents

db.restaurants.deleteMany({ "borough": "Brooklyn" });

2. Requêtes RESTful avec Flask et PyMongo


Installation et configuration

pip install flask pymongo

Créer l’application Flask

from flask import Flask, jsonify, request


from flask_pymongo import PyMongo
from bson.objectid import ObjectId

app = Flask(__name__)

# Connexion MongoDB
app.config["MONGO_URI"] = "mongodb://localhost:27017/restaurantsDB"
mongo = PyMongo(app)

Créer un restaurant (POST)

app.route('/restaurants', methods=['POST'])
def add_restaurant():
data = request.json

Untitled 4
if not data.get("name") or not data.get("borough") or not data.get("cuisin
e"):
return jsonify({"error": "Missing required fields"}), 400

restaurant_id = mongo.db.restaurants.insert_one(data).inserted_id
return jsonify({"message": "Restaurant added", "id": str(restaurant_id)}), 20
1

Exemple de requête

POST http://localhost:5000/restaurants
Content-Type: application/json

{
"name": "Sushi Place",
"borough": "Tokyo",
"cuisine": "Japanese",
"address": {
"street": "Shinjuku",
"zipcode": "160-0022"
}
}

Récupérer tous les restaurants (GET)

app.route('/restaurants', methods=['GET'])
def get_restaurants():
restaurants = list(mongo.db.restaurants.find({}, {"_id": 0}))
return jsonify(restaurants), 200

Exemple de requête

Untitled 5
GET http://localhost:5000/restaurants

Récupérer un restaurant spécifique par ID (GET)

@app.route('/restaurants/<id>', methods=['GET'])
def get_restaurant(id):
restaurant = mongo.db.restaurants.find_one({"_id": ObjectId(id)})
if not restaurant:
return jsonify({"error": "Restaurant not found"}), 404
return jsonify(restaurant), 200

Exemple de requête

GET http://localhost:5000/restaurants/65f2b34ae3c10c233b789012

Mettre à jour un restaurant (PUT)

python
CopierModifier
@app.route('/restaurants/<id>', methods=['PUT'])
def update_restaurant(id):
data = request.json
updated_data = {key: value for key, value in data.items() if key != "_id"}

result = mongo.db.restaurants.update_one({"_id": ObjectId(id)}, {"$set": up


dated_data})
if result.modified_count == 0:
return jsonify({"error": "No modifications made"}), 400

return jsonify({"message": "Restaurant updated"}), 200

Untitled 6
Exemple de requête

http
CopierModifier
PUT http://localhost:5000/restaurants/65f2b34ae3c10c233b789012
Content-Type: application/json

{
"cuisine": "Traditional Japanese"
}

Supprimer un restaurant (DELETE)

python
CopierModifier
@app.route('/restaurants/<id>', methods=['DELETE'])
def delete_restaurant(id):
result = mongo.db.restaurants.delete_one({"_id": ObjectId(id)})
if result.deleted_count == 0:
return jsonify({"error": "Restaurant not found"}), 404
return jsonify({"message": "Restaurant deleted"}), 200

Exemple de requête

http

DELETE http://localhost:5000/restaurants/65f2b34ae3c10c233b789012

3. Requêtes avancées

Untitled 7
Rechercher des restaurants avec filtres dynamiques (GET)

@app.route('/restaurants/search', methods=['GET'])
def search_restaurants():
name = request.args.get("name")
borough = request.args.get("borough")

query = {}
if name:
query["name"] = {"$regex": name, "$options": "i"} # Insensible à la cass
e
if borough:
query["borough"] = borough

results = list(mongo.db.restaurants.find(query, {"_id": 0}))


return jsonify(results), 200

Exemple de requête

GET http://localhost:5000/restaurants/search?name=pizza&borough=Brookly
n

4. Lancer l'application Flask

if __name__ == '__main__':
app.run(debug=True)

Untitled 8

You might also like