10 Kasım 2020 Salı

MongoDB aggregate metodu

Giriş
aggregate(...) pipeline ile tanımlanan adımları sıra ile işletir ve koşulu sağlayan nesneleri küme halinde döndürür. Bu pipeline aslında MapReduce ile aynı şey. Designing Data Intensive Applications kitabında açıklama şöyle. MongoDb 2.2 ile geliyor.
A usability problem with MapReduce is that you have to write two carefully coordinated JavaScript functions, which is often harder than writing a single query. Moreover, a declarative query language offers more opportunities for a query optimizer to improve the performance of a query. For these reasons, MongoDB 2.2 added support for a declarative query language called the aggregation pipeline.
En çok kullanılan stage (işlemler) listesi ve bunların SQL karşılıkları şöyle
project SELECT
match WHERE
group GROUP BY
sort ORDER BY
count COUNT
limit LIMIT
out SELECT INTO NEW_TABLE
User Defined Functions
Açıklaması şöyle
Within the aggregate() framework, users can define functions dynamically and invoke those functions ($function) as required. It’s all dynamic since the function definition is part of the query itself.

MongoDB also includes $accumulator operator where you can define a user-defined aggregation framework. This is quite useful in implementing business-specific aggregations unsupported by the language. PostgreSQL, Informix supported this and were called User Defined Aggregates (UDAs).
geoNear 
Örnek
geoNear kullanılarak en yakın noktaları bir küme şeklinde almak için şöyle yaparız.
db.new_stores.aggregate([
    { "$geoNear": {
        "near": {
            "type": "Point",
            "coordinates": [ -81.093699, 32.074673 ]
        }, 
        "maxDistance": 500 * 1609,
        "spherical": true,
        "distanceField": "distance",
        "distanceMultiplier": 0.000621371
    }}
]).pretty()
group
Örnek
Bir başka örnekte price alanı en büyük ve en küçük değere sahip iki nesne verilir. İki nesneyi yani aggregate kümesini tek nesneye indirgemek için _id alanı null verilir.
db.collection.aggregate([ 
    { "$group": { 
        "_id": null,
        "max": { "$max": "$price" }, 
        "min": { "$min": "$price" } 
    }}
])
match
aggregate ve match yazısına taşıdım.

skip
aggregate ve skip yazısına taşıdım

unwind
Nesnede dizi şeklindeki alanı teker teker dolaşmayı sağlar
Örnek
Şöyle yaparız. Burada her subject'in bir book dizisi var. Book dizisi dolaşılıyor ve project ediliyor. Daha sonra projection sort ediliyor.
db.Subject.aggregate([ 
  {
    $project:{
  "subject.subCode":1,
      "subject.book.bookTitle":1,
      "subject.book.publisher":1
  },
  {
    $unwind:"$subject.book"
  },
  {
    $sort:{
      "subject.subCode":1,
      "subject.book.publisher":-1
    }  
  }
]).pretty()
unwind + lookup
aggreagete ve lookup yazısına taşıdım

Hiç yorum yok:

Yorum Gönder