CS257
Chris Pollett
Sep 28, 2020
mongod --dbpath /usr/local/mongodb/data/db/
mongo
help
show dbs
use name_of_desired_databases
db.dropDatabase();
db.employees.insertOne({name : "Chris Pollett", born: 1970, salary: "too low"});
db.employees.insertMany([ {name : "Alice", born: 1990, salary: "just right"}, {name : "bob", born: 2000, salary: "too high"} ]);
db.createCollection(name, options);
my_options = {capped:true, size: 10000000, max:50}; db.createCollection("foo", my_options);Here capped size there is a maximum size of the collection, size is its size in bytes, max is the maximum number of documents.
db.name_of_collection.help()
show collections
db.collection_name.drop()
db.employees.find({}); //return all employees documents db.employees.find({born:1990, salary : "just right"}); // all employees born in //1990 whose salary is "just right" db.employees.find({born: {$gt : 1975}}); // all employees born after 1975 // also have $lt, $lte, $gte; logical operators //(use arrays) $and, $or, $not db.employees.find({and: [{born: {$gt : 1975}}, {born: {$lt : 2000}} ]}); db.employees.find({}, {name:1, _id:0}); // here we have project criteria where we list // fields we want with value 1, and those we don't with value 0
db.collection.remove(criteria) db.collection.update(filter, update, options)
db.employees.remove({born: 1970})
Which of the following is true?
import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import static com.mongodb.client.model.Filters.*; import static java.util.Arrays.asList; public class MongoDBExample { public static void main(String... args) { MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase("test"); // Delete all books first db.getCollection("books").deleteMany(new Document()); // Add some books db.getCollection("books").insertMany(new ArrayList<Document>() {{ add(getBookDocument("My First Book", "Wilfried", "Lemahieu", 12, new String[]{"drama"})); add(getBookDocument("My Second Book", "Seppe", "vanden Broucke", 437, new String[]{"fantasy", "thriller"})); add(getBookDocument("My Third Book", "Seppe", "vanden Broucke", 200, new String[]{"educational"})); add(getBookDocument("Java Programming for Database Managers", "Bart", "Baesens", 100, new String[]{"educational"})); }}); // Perform query FindIterable<Document> result = db.getCollection("books").find( and( eq("author.last_name", "vanden Broucke"), eq("genres", "thriller"), gt("nrPages", 100))); for (Document r: result) { System.out.println(r.toString()); // Increase the number of pages: db.getCollection("books").updateOne( new Document("_id", r.get("_id")), new Document("$set", new Document("nrPages", r.getInteger("nrPages") + 100))); } mongoClient.close(); } public static Document getBookDocument(String title, String authorFirst, String authorLast, int nrPages, String[] genres) { return new Document("author", new Document() .append("first_name", authorFirst) .append("last_name", authorLast)) .append("title", title) .append("nrPages", nrPages) .append("genres", asList(genres)); } }
db.my_collection .find(some_criteria) .sort({field_name1:1, field_name2:-1, ...}) .skip(50) .limit(5); // find returns a cursor, // which we modify to sort according to listed fields (1 = ASCENDING, -1=DESCENDING // then return the 50th through 55 result
// imagine salary had been reals rather that the strings // we used as a joke, we could calculate // for each year the total salary for that year for everyone // born after 1975 sorted by totals in descending fashion as: db.employees.aggregate([ { $match: { born: {$gt : 1975} } }, { $group: { _id: "$born", total: { $sum: "$salary" } } }, { $sort: { total: -1 } } ])
// Perform aggregation query AggregateIterable<Document> result = db.getCollection("books") .aggregate(asList( new Document("$group", new Document("_id", "$author.last_name") .append("page_sum", new Document("$sum", "$nrPages"))))); for (Document r: result) { System.out.println(r.toString()); }which returns the total number of pages written by each author:
Document{{_id=Lemahieu, page_sum=12}} Document{{_id=vanden Broucke, page_sum=637}} Document{{_id=Baesens, page_sum=100}}
my_criteria = {title: "text", description: "text"}; db.my_collection.createIndex(my_criteria);
db.my_collection.find( { $text: { $search: {"database mongodb"} } } )to look up titles or descriptions with the string "database mongodb" in it.
{ "title": "Databases for Beginners", "authors": ["J.K. Sequel", "John Smith"], "pages": 234 }becomes
{ "title": "Databases for Beginners", "authors": [{"first_name": "Jay Kay", "last_name": "Sequel", "age": 54}, {"first_name": "John", "last_name": "Smith", "age": 32} ], "pages": 234 }