简体   繁体   中英

How can I splice and sort a nested list in a mongodb collection?

I have the following document:

{
    "_id"423434234,
    "username":"Tom",
    "comments":
        [
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            },
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            },
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            },
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            },
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            },
            {
                "comment":"Hello",
                "dateCreated":2342362234523
            }
        ]
}

Using findOne I would like to query for the document by _id and only return the first 5 comments ordered by dateCreated DESC. I have tried this query:

findOne({"_id":ObjectId("517b9b749451a74ce661fa74")},{"comments":{"$slice":5}},{"$sort":{"comments.dateCreated":-1}})

It returns the first 5 comments but does not apply the desired sort.

The query you use is against the entire collection and the sort is being applied to the documents in that collection.

If you want to sort parts of the returned document the only way to do that is with aggregation framework .

Construct a pipeline similar to this:

db.collection.aggregate( [ { $match : { <your-find-expression> } }, 
                           { $unwind : "$comments" },
                           { $sort : { "comments.dateCreated" : -1 } },
                           { $limit : 5 }
] );

Optionally you can add $group to group the result set back into a single document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM