1

This is my dbcollection in mongodb

{
    "_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"
            ]
        }
    ]
}   

I cannot find list chapter sort by "dateUpload" in mongodb using java code. Please help.

1
  • You want only chapters list sorted order according to dateUpload is right? Commented Mar 29, 2015 at 10:24

2 Answers 2

2

Mongo $aggregation will solve your problem. Below query first $unwind your chapters array and then sort 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()

And for converting above query in java code formatt then follow below mongo aggregation java driver code . Java Driver and Aggregation Framework

Sign up to request clarification or add additional context in comments.

Comments

0

This should do it, using aggregate():

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

Extract the chapters subdocument with $project, then $unwind it to deconstruct the array and get each element, finally $sort them on dateUpload value (descending, use 1 for ascending order).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.