Reputation: 2045
I've two mongo collections - File
and Folder
.
Both have some common fields like name
, createdAt
etc. I've a resources
API that returns a response having items from both collections, with a type
property added. type
can be file
or folder
I want to support pagination and sorting in this list, for example sort by createdAt
. Is it possible with aggregation
, and how?
Moving them to a container collection is not a preferred option, as then I have to maintain the container collection on each create/update/delete
on either of the collection.
I'm using mongoose too, if it has got any utility function for this, or a plugin.
Upvotes: 0
Views: 578
Reputation: 11975
In this case, you can use $unionWith. Something like:
Folder.aggregate([
{ $project: { name: 1, createdAt: 1 } },
{
$unionWith: {
coll: "files", pipeline: [ { $project: { name: 1, createdAt: 1 } } ]
}
},
... // your sorting go here
])
Upvotes: 1