簡體   English   中英

在此示例中,如何使用Mongodb Aggregation?

[英]How can I use Mongodb Aggregation in this example?

我目前正在使用Python而不是MongoDB本身來構建許多結果。 我正在努力使自己了解“聚合”,但是我在努力掙扎。 這是我當前正在做的一個示例,MongoDB也許可以更好地處理它。

我有一套節目和一集劇集。 每個程序都有與之關聯的情節列表(DBRef)。 (由於程序和情節都非常復雜和深入,因此將情節存儲在自己的集合中,因此嵌入是不切實際的)。 每個情節都有一個持續時間(浮動)。 如果要查找某個節目的平均情節持續時間,請執行以下操作:

episodes = list(db.Episodes.find({'Program':DBRef('Programs',ObjectId(...))}))
durations = set(e['Duration'] for e in episodes if e['Duration'] > 0)
avg_mins = int(sum(durations) / len(durations) / 60

當節目有超過1000集時,這非常慢。 我有辦法在MongoDB中做到嗎?

以下是Mongo Shell格式的一些示例數據。 有3個情節屬於同一節目。 如何計算該節目的平均情節持續時間?

> db.Episodes.find({
    '_Program':DBRef('Programs',ObjectId('4ec634fbf4c4005664000313'))},
   {'_Program':1,'Duration':1}).limit(3)

{
    "_id" : ObjectId("506c15cbf4c4005f9c40f830"),
    "Duration" : 1643.856,
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313"))
}
{
    "_id" : ObjectId("506c15d3f4c4005f9c40f8cf"),
    "Duration" : 1598.088,
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313"))
}
{
    "_id" : ObjectId("506c15caf4c4005f9c40f80e"),
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313")),
    "Duration" : 1667.04
}

我已經弄清楚了,與將其全部拖入Python相比,它的速度非常快。

p = db.Programs.find_one({'Title':'...'})

pipe = [
        {'$match':{'_Program':DBRef('Programs',p['_id']),'Duration':{'$gt':0}}},
        {'$group':{'_id':'$_Program', 'AverageDuration':{'$avg':'$Duration'}}}
        ]

eps = db.Episodes.aggregate(pipeline=pipe)

print eps['result']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM