Вам может не понадобиться использовать $facet
для этого, попробуйте следующие запросы:
db.collection.aggregate([
{ "$match": { "productCategoryId": 34 } },
/** group on `productCategoryId` & get `minprice` on all docs & also push all docs into data array,
* Also you'll only have `"productCategoryId": 34` so need not to say ``"_id": "$productCategoryId" in group */
{
"$group": { "_id": "$productCategoryId", "minprice": { "$min": "$productPrice" }, data: { $push: "$$ROOT" } }
},
/** unwind data array */
{ $unwind: "$data" },
/** match the docs which have `data.productPrice` equivalent to `minprice` -
* If there are multiple matches you can use `$limit` after match stage to limit result */
{
$match: { $expr: { $eq: [ "$data.productPrice", "$minprice" ] } }
},
/** make `data` as new root of doc */
{ $replaceRoot: { newRoot: "$data" } }
])
Тест: mongoplayground
Если Вы думаете, что у вас будет слишком много документов, чтобы выполнить $unwind
, затем попробуйте выполнить запрос ниже:
db.collection.aggregate([
{ "$match": { "productCategoryId": 34 } },
/** group on `productCategoryId` & get `minprice` on all docs & also push all docs into data array */
{
"$group": { "_id": "$productCategoryId", "minprice": { "$min": "$productPrice" }, data: { $push: "$$ROOT" } }
},
/** re-create `data` array with matched docs */
{ $project: { data: { $filter: { input: "$data", cond: { $eq: [ "$$this.productPrice", "$minprice" ] } } } } },
/** unwind data array */
{ $unwind: "$data" },
/** make `data` as new root of doc */
{ $replaceRoot: { newRoot: "$data" } }
])
Тест: mongoplayground