如何在java中复杂的集合mongodb中排序并获取列表?

时间:2015-03-29 10:18:32

标签: java mongodb

这是我在mongodb中的dbcollection

{
    "_id" : 0,
    "name" : "+Anima",
    "author" : "MUKAI Natsumi",
    "type" : [ 
        "Adventure", 
        "Fantasy"
    ],
    "chapters" : [ 
        {
            "chapterName" : "+Anima 56",
            "chapterLink" : "http://...",
            "groupTranslate" : "Manga Palace Group",
            "dateUpload" : 1359478800000,
            "chapterNumber" : 56.0000000000000000,
            "images" : [ 
                 "img0", 
                "img1", 
                "img2", 
                "img3"
            ]
        }, 
        {
            "chapterName" : "+Anima 55",
            "chapterLink" : "http://....",
            "groupTranslate" : "Manga Palace Group",
            "dateUpload" : 1410109200000,
            "chapterNumber" : 55.0000000000000000,
            "images" : [ 
                "img0", 
                "img1", 
                "img2", 
                "img3"
            ]
        }
    ]
}   

我找不到使用java代码在mongodb中按“dateUpload”排序的列表章节。请帮忙。

2 个答案:

答案 0 :(得分:2)

Mongo $aggregation 将解决您的问题。下面首先查询$unwind您的chapters数组,然后排序dateUpload

    db.collectionName.aggregate({
    "$unwind": "$chapters" // unwind breaks the chapters array
}, {
    "$sort": {
    "chapters.dateUpload": -1 // then seperated chapters array sorted by dateUpload
    }
}, {
    "$group": {
    "_id": "$_id",
    "chapters": {
        "$push": "$chapters" // group used for grouping chapters array
    }
    }
}).pretty()

要在java代码格式中转换上述查询,请遵循以下mongo聚合java驱动程序代码。 Java Driver and Aggregation Framework

答案 1 :(得分:0)

这应该使用aggregate()

db.foo.aggregate( [ { $project: {chapters: 1} },
                    { $unwind: "$chapters" },
                    { $sort: {"chapters.dateUpload": -1} }
                  ] );

使用$project提取章节子文档,然后使用$unwind解构数组并获取每个元素,最后{date} {id} {9}}以降序,使用1升序)。