Paging and sorting an embedded array in a single document

I have a collection of documents, each with a unique key “AccountNum”

Inside of each of these account documents is an embedded array of documents called “Items” and each item document has a unique ItemId

I need to 1) find the specific document matching AccountNum then 2) page through the embedded items array and sort them by field name (e.g. sort by ItemId ascending or descending) and return only a “page” of that embedded array (e.g. return 50 items at a time out of an array of 1000, paging by batches of 50).

Is there a way to do this? I have tried different methods and just haven’t gotten it to work. I would prefer that Mongo does all the work and returns the data to the code (I’m working on a C# application).

I think I found my own solution:

db.getCollection(‘catalogs’).aggregate({$match: {“AccountNum”:“99999999”}},{$project:{“Items”:{$slice:["$Items",20,20]},"_id":false}})

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.