Skip to content

Instantly share code, notes, and snippets.

@Exilz
Last active March 11, 2018 17:27
Show Gist options
  • Save Exilz/ce30ab5486b3186a8574a93957b76fee to your computer and use it in GitHub Desktop.
Save Exilz/ce30ab5486b3186a8574a93957b76fee to your computer and use it in GitHub Desktop.
Commandes mongo cours MIW
// Commandes à réaliser dans un shell mongoDB, idéalement Intellishell de studio3T pour plus de clarté.
// Création de la collection
db.createCollection('movies');
// Insertions, fonctionnement du champ _id
db.articles.insert({ title: "Nom de l'article" }); // <- vérification de l'ajout + notes sur "_id"
db.articles.insert({ title: "Nom de l'article", subtitle: "Sous-titre" }); // notes sur les structures flexibles de mongo
db.articles.insert({ _id: "article-1", title: "Nom de l'article", subtitle: "Sous-titre" }); // <- necessité du champ _id
db.articles.insertMany([{ _id: "article-2", title: "Article 2" }, { "_id": "article-3", title: "Article 3" }]); // insertions multiples
// Mise à jour
db.articles.update({ _id: "article-1" }, { title: "màj titre" }); // <- champ "subtitle" disparu, remplacement complet
db.articles.update({ _id: "article-1" }, { title: "màj titre", subtitle: "sous-titre" }); // recréer le champ sous-titre
db.articles.update({ _id: "article-1" }, { $set: { subtitle: "màj sous-titre" } }); // màj uniquement du champ "subtitle"
// Suppression
db.articles.remove({ _id: "article-3" });
// Selection
db.articles.find({ _id: "article-1" }); // Retourne tous les documents correspondant à ce selecteur (tableau d'objets javascript)
db.articles.findOne({ _id: "article-1" }); // Retourne un seul doc (objet javascript)
db.articles.findOne({ _id: "article-1" }, { "title": 1 }); // Exemple de projection afin de ne retourner que le champ "title"
// Modifications avant démonstration des query selectors
db.articles.update({ _id: "article-2" }, { $set: { "year": 1990, "genres": ["comedy"] } });
db.articles.insert({ "_id": "article-3", title: "Article 3", "year": 2000, "genres": ["action", "historical"] });
// Query selectors
// Doc : https://docs.mongodb.com/manual/reference/operator/query/
db.articles.find({ genres: { $in: ['action'] }, year: { $gte: 2000 } }); // Films d'action année >= 2000 avec au moins le genre "action"
db.articles.find({ genres: { $in: ['action', 'comedy'] }, year: 1990 }); // Films de l'année 1990 avec au moins "action" ou "comedy"
db.articles.find({ year: { $exists: true }}); // Films qui ont une année renseignée
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment