=============================
GitHub on
https://github.com/romalopes/hw2-3
- MongoDB Course
Info:
https://education.mongodb.com/courses
Lenght of course: - 7 weeks
Using Maven
to run the project: mvn compile exec:java -Dexec.mainClass=course.BlogController
to test: mvn test
Using Gradle
to rum the project: gradle run
to test: gradle test
To create a project with gradle
- copy the directory Gradle to root
1: - gradle
2: wrapper
3: gradle-wrapper.jar
4: gradle-wrapper.properties
5: ide.gradle
6: - copy the btch file to root
7: gradlew (for X)
8: gradle.bat ( for windows)
9: - copy settings.gradle to root
10: Only this inside: rootProject.name = "NAME PROJECT"
- Week 1
- Suports
Based on Json Documents(key, values). It is a document database
In same document Dynamic Schema. Different collections of data.
- Scalability and performance VS Funcionality
Doesn't support joins and transactions. Documents are hierarchical
- Running
create a directory %MONGO_HOME%\data\db
1: %MONGO_HOME%/bin/mongo.config
2: ##store data here
3: dbpath=%MONGO_HOME%\data\db
4: ##all output go here
5: logpath=%MONGO_HOME%\log\mongo.log
6: ##log read and write operations
7: diaglog=3
- Server:
mongod --dbpath data\db
mongod --config %MONGO_HOME%\bin\mongo.config
As a server
mongod --config %MONGO_HOME%\bin\mongo.config --install
net start MongoDB
net stop MongoDB
mongod --remove (remove the service)
- Command line: mongo
Ex:
1: mongo test(connects to mongodb already in test collection)
2: use test (switches to test collection)
3: show collections
4: (collection) (command)
5: db.objects. save({a:1, b:2, c:3})
6: db.objects. save({a:4, b:5, c:6, d:7, e:['a','b']})
7: db.objects.find() <- return all documents
8: db.objects.find({a:1}) <- Return all documents that have this element
9: db.course.hello.save({'name','maths'})
10: db.course.hello.find()
- Json
Types of Data
- Array -> list of items -> [...]
- Dictionaries ->associative maps {key:value} -> {name:"value",city:"value", interests:[ ___, ___, ___]
- Embeded data into documents
If the embeded data exceed 16Mb, because each document should have the maximum of 16Mb
Home Work:
1 - 42
2- 2,3,5
3-366
4- 2805
- Week 2
- CRUD
Create=Insert. Read=Find. Update=Update. Delete=Remove
Does not have a language such as SQL.
1: - db.people.insert( doc )
2: - db.people.find()
3: - db.people.findOne({"name": "Anderson"}, {"name":true,"_id":false})
- all object has a primary key called (_id)
- BSON - Binary JSON Object
- Query
- $gt, $lt,
1: db.people.findOne({name:{$gt: "B", $lt:"D"}})
2: db.people.findOne({name:{$gt: "B"}, {name:{$lt:"D"}} }) --Will return all docs less than D. Ignore the first statement.
- exists
- To verify if a field exists
- db.people.findOne({name:{ $exists : true}}) -- return all documents that has the field name.
- regex
- db.people.find({name: { $regex : "^A"}}) -> returns everything that starts with A.
ex:db.users.find( {name: {$regex:"q"}, email: {$exists:true} } )
- or //ends with e
- db.people.find( { $or : [ {name: { $regex : "e$" } } , {age : {$exists: true}]})
- db.scores.find( {$or : [ {score : {$lt: 50}}, {score : {$gt: 90}} ]})
- and
- all - return the documents that have all the specified elements in a array
db.accounts.find( { favorites : { $all, [ "a", "b", "c" ] } } )
- in - return all documents that has on of the objects IN a array
db.accounts.find( { name : { $in, [ "Anderson", "Cida"] } } ) -- returns the docs that have Anderson and Cida
- Queries
db.users.find( {email : {work: "romalopes@yahoo.com.br" } } )
or
db.users.find( {email.work: "romalopes@yahoo.com.br" } )
- Cursor
1: db.people.insert( {name: "Anderson", email : {work:"111", home:"222"}});
2: db.people.insert( {name: "Cida", email : {work:"111", home:"222"}});
3: - cur = db.people.find(); null; //NULL avoid the return.
4: - cur.limit(5); null; get only 5 elements.
5: - cur.sort( {name: -1 }); null;
6: - cur.sort( {name: -1 }).limit(5); null;
7: - while(cur.hasNext()) printjson(cur.next());
8: - db.scores.find( { type : "exam" } ).sort( { score : -1 } ).skip(50).limit(20)
- count
db.score.count({type:"exam"})
- db.scores.count( {"type":"essay", score: {$gt: 90 } } )
- Update
- db.people.update( { name: "Anderson"} , {name:"Anderson Lopes", address:"114 Hargrave"})
- Creates, remove and replace all the attributes.
- $set
db.people.update( { name: "Anderson"} , {$set: {age:30}} )
- set only the values we want to change.
db.people.update( { name: "Anderson"} , {$inc: {age:3} } )
- increment 3 in age.
- ex:
1: db.arrays.insert( {_id:0, a:[1,2,3,4]});
2: db.arrays.update( {_id:0, {$set : {"a.2" : 5 }});
3: change the third element from 3 to 5.
4: db.arrays.update( {_id:0, {$push : {a : 6 }});
5: add at the end of array
6: db.arrays.update( {_id:0, {$pop : {a : 1 }}); //remove the last element
7: db.arrays.update( {_id:0, {$pop : {a : -1 }}); //remove the first element
8: db.arrays.update( {_id:0, {$pushAll : {a : [6, 7, 8, 9 }});
9: db.arrays.update( {_id:0, {$pull : {a : 3} }); //remove the element that the value is 3
10: db.arrays.update( {_id:0, {$pullAll : {a : [6, 7, 8, 9 }}); // remove all elements with the values in the second array
- $unset (remove a field from a collection)
db.people.update( { name: "Anderson"} , {$unset: {age:1} } )
- Multi-update
Update multiple documents
db.people.update( {} , {$set :{"title": "Dr" } }, {multi: true} );
db.scores.update ( { score: {$lt:70} }, {$inc: {score:20}}, {multi:true});
- Remove a database
1: use DATABASE
2: db.dropDatabase()
- remove
1: db.people.remove() //remove everything from the collection.
2: db.people.drop() //faster than remove
3: db.people.remove( {name:"Alice"})
4: db.people.remove( {name: {$gt: "M" }} )
5: db.scores.remove( {score: { $lt: 60 }})
6: - db.runCommand( {getLastError:1})
return the last result of a command. It can be a error, a result of a update and so on.
With Java
CRUD
1: INSERT DBOBject(interface) . BasicDBObject with is a LinkedHashMap<String, Object>
2: BasicDBObject doc = new BasicDBObject();
3: doc.put("userName", "anderson");
4: doc.put("birthDate", new Date(2344242));
5: doc.put("programmer", true);
6: doc.put("age", 8);
7: doc.put("languages", Arrays.asList("Java", "C++"));
8: doc.put("address", new BasicDBObject("street", "114 Hargrave")
9: .append("town", "Paddington")
10: .append("zipCode", 2021));
11: { "_id" : "user1",
12: "interests" : [ "basketball", "drumming"] }
13: new BasicDBObject("_id", "user1").append("interests", Arrays.asList("basketball", "drumming"));
FIND
1: DB courseDB = client.getDB("course");
2: DBCollection collection = courseDB.getCollection("findCriteriaTest");
3: collection.drop();
4: for(int i=0; i<10; i++) {
5: collection.insert(new BasicDBObject( "x", new Random().nextInt(2)).
6: append("y", new Random().nextInt(100)));
7: }
8: System.out.println("\n Find All");
9: DBCursor cursor1 = collection.find();
10: try {
11: while(cursor1.hasNext()) {
12: DBObject all = cursor1.next();
13: System.out.println(all);
14: }
15: } finally {
16: cursor1.close();
17: }
18: DBObject query = new BasicDBObject("x", 0)
19: //AND in Y
20: .append("y", new BasicDBObject("$gt", 10).append("$lt", 90));
21: //OR
22: QueryBuilder builder = QueryBuilder.start("x").is(0)
23: .and("y").greaterThan(10).lessThan(90);
24: System.out.println("\n Count");
25: long count = collection.count(query); // builder.get()
26: System.out.println(count);
27: System.out.println("Find One");
28: DBObject one = collection.findOne(query); //builder.get()
29: System.out.println(one);
30: System.out.println("\n Find All");
31: DBCursor cursor = collection.find(query); //builder.get()
32: try {
33: while(cursor.hasNext()) {
34: DBObject all = cursor.next();
35: System.out.println(all);
36: }
37: } finally {
38: cursor.close();
39: }
40: for(int i=0; i<10; i++) {
41: collection.insert(new BasicDBObject( "_id", i).
42: append("start",
43: new BasicDBObject("x", new Random().nextInt(90) + 10)
44: .append("z", new Random().nextInt(90) + 10)
45: ).append("end",
46: new BasicDBObject("x", new Random().nextInt(90) + 10)
47: .append("z", new Random().nextInt(90) + 10)
48: )
49: );
50: }
51: //QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);
52: //DBCursor cursor = collection.find(builder.get(),
53: // new BasicDBObject("start.x", true).append("_id", false).append("end.z", true));
54: DBCursor cursor = collection.find()
55: .sort(new BasicDBObject("_id", -1)).skip(5).limit(3);
56: DBCursor cursor = collection.find()
57: .sort(new BasicDBObject("start.x", -1).append("end.z",1)).skip(5).limit(3);
UPDATE
REMOVE
1: //query
2: collection.update(new BasicDBObject("_id", "alice"),
3: new BasicDBObject("age", 35));//update
4: collection.update(new BasicDBObject("_id", "alice"),
5: new BasicDBObject("gender", "Female"));//update
6: //will remove the gender - Female and insert the Title Srs
7: collection.update(new BasicDBObject("_id", "alice"),
8: new BasicDBObject("$set" , new BasicDBObject("Title", "Srs")));//update
9: //To insert, it is needed two last parameters
10: collection.update(new BasicDBObject("_id", "frank"), //to insert
11: new BasicDBObject("$set" , new BasicDBObject("Title", "Sr")), true, false);//update
12: collection.update(new BasicDBObject(),//every document //to update
13: new BasicDBObject("$set" , new BasicDBObject("Graduation", "Masters")), false, true);//update
14: //collection.remove(new BasicDBObject());
15: collection.remove(new BasicDBObject("_id", "alice"));
- About blog
View - ftl - freemarker
controller/model java/spark.
- Home Work -
1 - db.grades.find({score:{$gte:65}}).sort( { score : 1 } ).limit(1)
2 - 124
3 - fhj837hf9376hgf93hf832jf9
- Week 3
- MongoDB Schema Design
Application-Driven Schema
. Features
Rich Documents
Pre join data for fast access
No Joing
No Constraina like MySql
Atomic operations(no transactions)
No Declared Schema
Nenhum comentário:
Postar um comentário