mongodb query to show subdocument as maindocument and having pagination with it mongodb query to show subdocument as maindocument and having pagination with it mongoose mongoose

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 objects produk and foto_profil using $mergeObjects and replace the root
  {    $replaceRoot: {      newRoot: {        $mergeObjects: [{ foto_profil: "$foto_profil" }, "$produk"]      }    }  },  { $skip: skip * limit },  { $limit: limit }

Playground


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 objects produk and foto_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 }

Playground


maybe you can do this after lookup:

  1. $unwind produk (where the produk still on array type, then unwind it).
  2. $group: { _id: nama_produk, etc... }
  3. $project ...... or whatever you wanna do with.

so you can get the list of group by nama_produk as an _id.