MongoDB – M001

show dbs
//veritabanlarını listeler

use sample_training
//veritabanına geçiş yapar

show collections
//collection listeler

db.inspections.findOne();
//tek kayıt getirir.

db.zips.find({"state": "NY"})
//koşula uygun tüm kayıtları getirir.

it
//dönen kayıtlar 20’şerli olarak listelenir, sonraki sayfaya geçmek için kullanılır.

db.zips.find({"state": "NY"}).count()
//count almak için kullanılır.

db.zips.find({"state": "NY", "city": "ALBANY"})
db.zips.find({"state": "NY", "city": "ALBANY"}).pretty()
//sonucu okunabilir göstermek için, kullanılır.

db.inspections.insert({
"id" : "10021-2015-ENFO",
"certificate_number" : 9278806,
"business_name" : "ATLIXCO DELI GROCERY INC.",
"date" : "Feb 20 2015",
"result" : "No Violation Issued",
"sector" : "Cigarette Retail Dealer - 127",
"address" : {
"city" : "RIDGEWOOD",
"zip" : 11385,
"street" : "MENAHAN ST",
"number" : 1712}
})

db.inspections.find({ "test": 1 })
//tek kayıt insert

db.inspections.insert([ { "test": 1 }, { "test": 2 }, { "test": 3 } ])
//birden fazla kayıt insert

db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }])
//2. kayıt duplicate olarak hata alır ve 3. kayıda geçiş yapılmadan process durur.

db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }],{ "ordered": false })
//1. ve 2. kayıt duplicate olarak hata alır, 3. kayıt insert edilir. Çünkü sıralı olarak değil bütün işlemler yapılır.

//updateMany eşleşen bütün kayıtları update eder.
//updateOne eşleşen kayıtlardan birini update eder.
//$inc operatörü var olan değeri arttırmak için kullanılır.


//update all documents in the zips collection where the city field is equal to “HUDSON” by adding 10 to the current value of the “pop” field.
db.zips.updateMany({ "city": "HUDSON" }, { "$inc": { "pop": 10 } })

//update a single document in the zips collection where the zip field is equal to “12534” by setting the value of the “pop” field to 17630.
db.zips.updateOne({ "zip": "12534" }, { "$set": { "pop": 17630 } })

//update a single document in the zips collection where the zip field is equal to “12534” by setting the value of the “popupation” field to 17630.
db.zips.updateOne({ "zip": "12534" }, { "$set": { "population": 17630 } })

//find all documents in the grades collection where the student_id field is 151 , and the class_id field is 339.
db.grades.find({ "student_id": 151, "class_id": 339 }).pretty()

//update one document in the grades collection where the student_id is 250 *, and the class_id field is 339,
//by adding a document element to the “scores” array.
db.grades.updateOne({ "student_id": 250, "class_id": 339 },{ "$push": { "scores": { "type": "extra credit","score": 100 }}})

//delete all the documents that have test field equal to 1.
db.inspections.deleteMany({ "test": 1 })

//delete one document that has test field equal to 3.
db.inspections.deleteOne({ "test": 3 })

//inspect what is left of the inspection collection.
db.inspection.find().pretty()

//drop the inspection collection.
db.inspection.drop()

//https://docs.mongodb.com/manual/reference/operator/query-comparison/
$eq //matches values that are equal to a specified value.
$gt //matches values that are greater than a specified value.
$gte //matches values that are greater than or equal to a specified value.
$in //matches any of the values specified in an array.
$lt //matches values that are less than a specified value.
$lte //matches values that are less than or equal to a specified value.
$ne //matches all values that are not equal to a specified value.
$nin //matches none of the values specified in an array.

//find all documents where the tripduration was less than or equal to 70 seconds and the usertype was
//Customer using a redundant equality operator:
db.trips.find({ "tripduration": { "$lte" : 70 },"usertype": { "$eq": "Customer" }}).pretty()

//https://docs.mongodb.com/manual/reference/operator/query-logical/
$and //joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not //inverts the effect of a query expression and returns documents that do not match the query expression.
$nor //joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or //joins query clauses with a logical OR returns all documents that match the conditions of either clause.

db.routes.find({ "$and": [ { "$or" :[ { "dst_airport": "KZN" },{ "src_airport": "KZN" }] },
{ "$or" :[ { "airplane": "CR2" },{ "airplane": "A81" } ] } ]}).pretty()

//https://docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr
//find all documents where the trip started and ended at the same station:
db.trips.find({ “$expr”: { “$eq”: [ “$end station id”, “$start station id”] }}).count()

//find all documents where the trip lasted longer than 1200 seconds, and started and ended at the same station:
db.trips.find({ “$expr”: { “$and”: [ { “$gt”: [ “$tripduration”, 1200 ]},
{ “$eq”: [ “$end station id”, “$start station id” ]}]}}).count()

db.companies.find({“$expr”:{“$eq”:[“$permalink”,”$twitter_username”]}}).count()

//array’lerde tek kayıt verilirse, o kaydı içeren bütün dökümanlar gelir.
//array’lerde birden fazla kayıt verilirse, verildiği sıra ile arama yapılır.
// $all eklenirse koşullar içeren bütün dökümanlar sırası önemsemeden getirilir.
//find all documents with exactly 20 amenities which include all the amenities listed in the query array:
db.listingsAndReviews.find({ “amenities”: {
“$size”: 20,
“$all”: [ “Internet”, “Wifi”, “Kitchen”,
“Heating”, “Family/kid friendly”,
“Washer”, “Dryer”, “Essentials”,
“Shampoo”, “Hangers”,
“Hair dryer”, “Iron”,
“Laptop friendly workspace” ]
}
}).pretty()

//projection kısmında field’lar 0 veya 1 değer alır. SELECT listesinde field göstermek veya göstermemek için.
db.documents.find({},{})

//find all documents with exactly 20 amenities which include all the amenities listed in the query array, and display their price and address:
db.listingsAndReviews.find({ “amenities”:
{ “$size”: 20, “$all”: [ “Internet”, “Wifi”, “Kitchen”, “Heating”,
“Family/kid friendly”, “Washer”, “Dryer”,
“Essentials”, “Shampoo”, “Hangers”,
“Hair dryer”, “Iron”,
“Laptop friendly workspace” ] } },
{“price”: 1, “address”: 1}).pretty()

//find all documents that have Wifi as one of the amenities only include price and address in the resulting cursor:
db.listingsAndReviews.find({ “amenities”: “Wifi” },
{ “price”: 1, “address”: 1, “_id”: 0 }).pretty()

//fFind all documents that have Wifi as one of the amenities only include price and address in the resulting cursor, also exclude "maximum_nights". *This will be an error:
db.listingsAndReviews.find({ “amenities”: “Wifi” },
{ “price”: 1, “address”: 1,
“_id”: 0, “maximum_nights”:0 }).pretty()

//find all documents where the student in class 431 received a grade higher than 85 for any type of assignment:
db.grades.find({ “class_id”: 431 },
{ “scores”: { “$elemMatch”: { “score”: { “$gt”: 85 } } }}).pretty()

//find all documents where the student had an extra credit score:
db.grades.find({ “scores”: { “$elemMatch”: { “type”: “extra credit” } }}).pretty()

//sub document query
db.trips.findOne({ “start station location.type”: “Point” })

db.companies.find({ “relationships.0.person.last_name”: “Zuckerberg” },
{ “name”: 1 }).pretty()

db.companies.find({ “relationships.0.person.first_name”: “Mark”,
“relationships.0.title”: { “$regex”: “CEO” } },
{ “name”: 1 }).count()

db.companies.find({ “relationships.0.person.first_name”: “Mark”,
“relationships.0.title”: {“$regex”: “CEO” } },
{ “name”: 1 }).pretty()

db.companies.find({ “relationships”:
{ “$elemMatch”: { “is_past”: true,
“person.first_name”: “Mark” } } },
{ “name”: 1 }).pretty()

db.companies.find({ “relationships”:
{ “$elemMatch”: { “is_past”: true,
“person.first_name”: “Mark” } } },
{ “name”: 1 }).count()

db.trips.findOne({“start station location”:{“$elemMatch”:{“coordinates”:”-74″}}})

//find all documents that have Wifi as one of the amenities. Only include price and address in the resulting cursor.
db.listingsAndReviews.find({ “amenities”: “Wifi” },{ “price”: 1, “address”: 1, “_id”: 0 }).pretty()

//aggregate grouplama ve veri hesaplama vs için kullanılan operatör
//aggregate yazılırken sıralama önemlidir (match,project,group)
//using the aggregation framework find all documents that have Wifi as one of the amenities*. Only include*price and address in the resulting cursor.
db.listingsAndReviews.aggregate([
{ “$match”: { “amenities”: “Wifi” } },
{ “$project”: { “price”: 1, “address”: 1, “_id”: 0 }}]).pretty()

//find one document in the collection and only include the address field in the resulting cursor.
db.listingsAndReviews.findOne({ },{ “address”: 1, “_id”: 0 })

//project only the address field value for each document, then group all documents into one document per address.country value.
db.listingsAndReviews.aggregate([ { “$project”: { “address”: 1, “_id”: 0 }},
{ “$group”: { “_id”: “$address.country” }}])

//project only the address field value for each document, then group all documents into one document per address.country value, and count one for each document in each group.
db.listingsAndReviews.aggregate([
{ “$project”: { “address”: 1, “_id”: 0 }},
{ “$group”: { “_id”: “$address.country”,”count”: { “$sum”: 1 } } }
])

//room_type alanına sahip olan dökümanları gruplayım göster
db.listingsAndReviews.aggregate({“$project”:{“room_type”:1,”_id”:0}},{“$group”:{“_id”:”$room_type”}})

db.listingsAndReviews.aggregate([
{“$project”:{“room_type”:1,”_id”:0}},
{“$group”:{“_id”:”$room_type”,”count”: { “$sum”: 1 }}}])

//1 kayıt gösterir
db.zips.find().sort({ “pop”: 1 }).limit(1)

//desc sıralayıp 1 kayıt gösterir
db.zips.find().sort({ “pop”: -1 }).limit(1)

db.zips.find().sort({ “pop”: -1 }).limit(10)

db.zips.find().sort({ “pop”: 1, “city”: -1 })

//sorgular için uygun index’ler performans kazanamı sağlayacaktır, daha az memory ve cpu kullanımı
db.trips.find({ “birth year”: 1989 })

db.trips.createIndex({ “birth year”: 1 })

db.trips.find({ “start station id”: 476 }).sort( { “birth year”: 1 } )

db.trips.createIndex({ “start station id”: 476, “birth year”: 1 })

//upsert : true olduğunda eğer belirtilen koşullarda döküman bulunamazsa yeni bir döküman oluşturulur.
db.iot.updateOne({ “sensor”: r.sensor, “date”: r.date,
“valcount”: { “$lt”: 48 } },
{ “$push”: { “readings”: { “v”: r.value, “t”: r.time } },
“$inc”: { “valcount”: 1, “total”: r.value } },
{ “upsert”: true })

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

This site uses Akismet to reduce spam. Learn how your comment data is processed.