2013-03-08 77 views
1

我有存儲在MongoDB中收集類似的一些數據:查找文檔

{"_id": 1, "category": "food", "name": "chips", "price": 1.50, "effectiveDate": ISODate("2013-03-01T07:00:00Z")} 
{"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} 
{"_id": 3, "category": "food", "name": "chips", "price": 1.90, "effectiveDate": ISODate("2013-03-10T07:00:00Z")} 
{"_id": 4, "category": "beverage", "name": "pop", "price": 2.00, "effectiveDate": ISODate("2013-03-01T07:00:00Z")} 
{"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} 
{"_id": 6, "category": "beverage", "name": "pop", "price": 1.80, "effectiveDate": ISODate("2013-03-10T07:00:00Z")} 

在MongoDB中,我將如何去寫一個查詢,都將返回一個活躍的文件在特定的日期,按類別分組?

如果我指定的2013年3月6日,我期望看到的結果:

{"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} 
{"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} 

我是新來蒙戈並一直在努力做到這一點使用組,彙總和MapReduce但都被剛剛紡在圈子裏。

+0

你想什麼做與其他領域如價格?最高價格?最低價格? – 2013-03-08 08:02:56

+0

我不需要任何計算。我只是在尋找適用於特定時間點的文件。 – ReKo 2013-03-08 16:47:44

回答

1

爲了給你一個真正的好答案,我需要你的代碼的更多細節以及你正在嘗試做什麼。但是如果我理解正確,我認爲你可以僅使用聚合框架來解決這個問題。您應該知道聚合框架使用管道概念,換句話說,每個步驟的結果都用作以下條目。

我的查詢:

db.yourcollection.aggregate([ 

    /* First exclude everything that is superior to a given date */ 
    {$match:{effectiveDate:{$lte:new Date(2013,2,6)}}}, 

    /* Sort the rest by date, descending */ 
    {$sort:{effectiveDate:-1}}, 

    /* Group by name+category and grab only the first result 
     (the newest below that date) */ 
    {$group:{_id:{name:'$name',category:'$category'}, effectiveDate:{$first:"$effectiveDate"},price:{$first:"$price"}}}, 

    /* You said you want the results grouped by category. 
     This last $group does that and returns all matching products inside an array 
     It also removes the duplicates */ 
    {$group:{_id:'$_id.category',products:{$addToSet:{name:"$_id.name",price:"$price",effectiveDate:"$effectiveDate"}}}} 

]) 

輸出是這樣的:

{ 
    "result": [ 
     { 
      "_id": "food", 
      "products": [ 
       { 
        "name" : "chips", 
        "price" : 1.75, 
        "effectiveDate" : ISODate("2013-03-05T07:00:00Z") 
       } 
      ] 
     }, 
     { 
      "_id" : "beverage", 
      "products": [ 
       { 
        "name" : "pop", 
        "price" : 2.25, 
        "effectiveDate" : ISODate("2013-03-05T07:00:00Z") 
       } 
      ] 
     } 
    ], 
    "ok":1 
} 

可以更改最終輸出對矯正最後$group或使用$project

+0

感謝您花時間解決此問題。我會執行你的發現,並讓你知道它是否適合我。 – ReKo 2013-03-20 16:07:43