vishesh
vishesh

Reputation: 2045

MongoDB paginate 2 collections together on common field

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

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

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

Related Questions