mongodb query to show subdocument as maindocument and having pagination with it
I am not sure with exact requirement, but I can guess 2 options,
- Assuming Variables:
let skip = 0;let limit = 10;
First Option:
- remove
$group
stage from the end and start after$unwind
stage $replaceRoot
to merge objectsproduk
andfoto_profil
using$mergeObjects
and replace the root
{ $replaceRoot: { newRoot: { $mergeObjects: [{ foto_profil: "$foto_profil" }, "$produk"] } } }, { $skip: skip * limit }, { $limit: limit }
Second Option:
- remove
$group
stage from the end and start after$unwind
stage $group
by toko id and produk id, this will group produk and get unique first produk$replaceRoot
to merge objectsproduk
andfoto_profil
using$mergeObjects
and replace the root
{ $group: { _id: { _id: "$_id", produk_id: "$produk._id" }, root: { $first: "$$ROOT" } } }, { $replaceRoot: { newRoot: { $mergeObjects: [{ foto_profil: "$root.foto_profil" }, "$root.produk"] } } }, { $skip: skip * limit }, { $limit: limit }
maybe you can do this after lookup:
- $unwind produk (where the produk still on array type, then unwind it).
- $group: { _id: nama_produk, etc... }
- $project ...... or whatever you wanna do with.
so you can get the list of group by nama_produk as an _id.