MongoDB返回每个id的最新完整文档(包含子文档数组等所有字段的完整文档对象)

时间:2017-08-09 07:35:13

标签: mongodb mongoose aggregation-framework

有超过1000个文件,即水果对象。 我需要获得最新文档(完整对象),即每个水果的采摘日期。在这里您可以使用示例

{
    "fruit":"apple",
    "pluckedDate": "2017-05-05 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 0.0,
            "weight" : 0.0
        }, 
        {
            "type" : 2,
            "size" : 10.0,
            "weight" : 77.0
        }, 
        {
            "type" : 3,
            "size" : 10.0,
            "weight" : 42.0
        }
    ]
},{
    "fruit":"apple",
    "pluckedDate": "2017-05-06 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 0.0,
            "weight" : 0.0
        }, 
        {
            "type" : 2,
            "size" : 102.0,
            "weight" : 377.0
        }, 
        {
            "type" : 3,
            "size" : 103.0,
            "weight" : 142.0
        }
    ]
},{
    "fruit":"orange",
    "pluckedDate": "2017-05-05 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 0.0,
            "weight" : 0.0
        }, 
        {
            "type" : 2,
            "size" : 10.0,
            "weight" : 37.0
        }, 
    ]
},{
    "fruit":"orange",
    "pluckedDate": "2017-05-04 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 11.0,
            "weight" : 89.0
        }, 
        {
            "type" : 2,
            "size" : 54.0,
            "weight" : 567.0
        }, 
    ]
}

我需要最终输出从mongoDB返回最新的完整文档,如下例所示:

{
    "fruit":"apple",
    "pluckedDate": "2017-05-06 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 0.0,
            "weight" : 0.0
        }, 
        {
            "type" : 2,
            "size" : 102.0,
            "weight" : 377.0
        }, 
        {
            "type" : 3,
            "size" : 103.0,
            "weight" : 142.0
        }
    ]
},{
    "fruit":"orange",
    "pluckedDate": "2017-05-05 18:29:03.232Z",
    "desc":[
        {
            "type" : 1,
            "size" : 0.0,
            "weight" : 0.0
        }, 
        {
            "type" : 2,
            "size" : 10.0,
            "weight" : 37.0
        }, 
    ]
}

我尝试使用聚合但是我发现完整文档没有返回,或者我的聚合查询可能是错误的。

或者除了MongoDB中的聚合外还有其他方法可以实现这个目标

聚合查询如下:

fruitCollect.aggregate([
    //query param
    {"$sort":
      {"plukedDate":1}
    },
    { "$group": {
        "_id": "$fruit",
        "plukedDate": { "$last": "$plukedDate" },

        }
    },{
        "$project":{
            "fruit":1,
            "plukedDate":1,
            "desc":1
        }
    }
]).exec()

我完全陷入困境,感谢任何帮助。

0 个答案:

没有答案