2017-03-15 197 views
0

我是MongoDB的新手。我有要求从一系列产品中获取特定日期的最新更新产品。 下面是我的需求的JSON对象。MongoDB中的聚合查询

{ 
    "_id": ObjectId("10001"), 
    "product": [{ 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 1, 
     "updatedDate": "14-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 2, 
     "updatedDate": "14-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 1, 
     "updatedDate": "15-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 2, 
     "updatedDate": "15-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 3, 
     "updatedDate": "15-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 4, 
     "updatedDate": "15-03-2017" 
    }] 
}, { 
    "_id": ObjectId("10002"), 
    "product": [{ 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 1, 
     "updatedDate": "14-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 2, 
     "updatedDate": "14-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 1, 
     "updatedDate": "15-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 2, 
     "updatedDate": "15-03-2017" 
    }, { 
     "image": "./../../../prod1.html", 
     "name": "product", 
     "version": 3, 
     "updatedDate": "15-03-2017" 
    }] 
}, 
} 

我需要一个查询 - 它将检索带有最新版本的14-03-2017产品。

预期的结果是:

{ 
"_id" : ObjectId("10001"), 
"product" : [ 
    {"image" : "./../../../prod1.html","name" : "product","version" : 4,"updatedDate":"15-03-2017"} 
]}, 
{ 
"_id" : ObjectId("10002"), 
"product" : [ 
    {"image" : "./../../../prod1.html","name" : "product","version" : 3,"updatedDate":"15-03-2017"} 
]} 

这将是高度赞赏有人能帮助我与聚合函数来获得预期的结果。

+0

需要取得与最新的日期和最新版本的产品在该日期(日期将包含多个版本) – yuvan

+0

什么是你的MongoDB服务器版? – chridam

回答

1

使用aggregate命令,

db.collection.aggregate([{ 
    $unwind: "$product" 
}, { 
    $sort: { 
     "product.updatedDate": 1 
    } 
}, { 
    $group: { 
     _id: "$_id", 
     product: { 
      $last: "$product" 
     } 
    } 
}]) 

输出:

{ 
    "_id" : ObjectId("10002"), 
    "product" : { 
     "image" : "./../../../prod1.html", 
     "name" : "product", 
     "version" : 3, 
     "updatedDate" : "15-03-2017" 
    } 
} 
{ 
    "_id" : ObjectId("10001"), 
    "product" : { 
     "image" : "./../../../prod1.html", 
     "name" : "product", 
     "version" : 4, 
     "updatedDate" : "15-03-2017" 
    } 
} 
+0

你好朋友,非常感谢。它工作完美。感谢您的直接回复。 – yuvan