In this lecture we analyze document oriented databases. In particular we consider why there are the first approach to nosql and what are the main features. Then, we analyze as example MongoDB. We consider the data model, CRUD operations, write concerns, scaling (replication and sharding).
Finally we presents other document oriented database and when to use or not document oriented databases.
13. Sort
• to sort by and the corresponding sort type:
– e.g. 1 for ascending
– and -1 for descending.
• Example:
– db.places.find().sort({"name" : 1, "comments.score" : -1})
13
14. Updating
• We can use the update() method to update
documents of a collection. The method accepts as its
parameters:
– a filter document to match the documents to update,
– an update document to specify the modification to
perform, and
– an options parameter (optional).
14
16. Update Multi
16
db.places.update(
{name : "10gen HQ"},
{ $push :
{ comments :
{ author : "steve",
date : 6/26/2015,
text : "Office hours are great!"
}
}
},
{ multi: true}
)
17. Remove
• We can use the remove() method to remove
documents from a collection.
• The method takes a conditions document that
determines the documents to remove.
• To specify a remove condition,
17
19. Drop Collections and DB
• The drop() method to drop a collection, including any
indexes
– db.places.drop()
• Drop a db
– use test
– db.dropDatabase()
19
21. Regular Expression
21
// Regular Expressions
> db.posts.find({'comments.author': /^Fa/}){ _id :
ObjectId("4c4ba5c0672c685e5e8aabf3"),
name : "10gen HQ", address : "578 Broadway 7th Floor", city :
"New York",
zip : "10011",
comments : [ {
author : ”Fabio",
date : "Sat Apr 25 2010 20:51:03",
22. Cursor
• How to get a cursor:
– var it = db.venues.find()
• Methods
– next
– hasNext
22
23. Aggregation
• Group Documents by a Field and Calculate Count
23
db.venues.aggregate(
[
{ $group: { "_id": "$location.city", "count": { $sum: 1 } } }
]
)
24. Indexes
• By default index on collections are only on the _id
• the createIndex() method is used to create an index on a
collection
• Indexes can support the efficient execution of queries.
– For an ascending index type, specify 1 for <type>.
– For a descending index type, specify -1 for <type>.
24
26. Create a Compound Index
26
db.venues.createIndex({"country": 1, "distance": -1})
{
"createdCollectionAutomatically" :
false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
Upon successful index creation, the "numIndexesAfter"
value is one greater than the "numIndexesBefore" value.