Good day all,
I'm trying to return some n random item from a nested array in an aggregation pipeline, however, I cannot seem to figure it out. all documentation from mongodb about random is at the document level, $sample which will return a number of documents based on the sample size defined. I want to return an n random number from an array within one document and then in a subsequent stage perform a $lookup stage. example below.
this is the document
{
_id: "61005f388308a717883ad3d2",
...................
...................
"productLine": {
"product": [
"5fefa2556308ab102854baf7",
"5fefa2556308ab102854baf8",
"5fefa2556308ab102854baf9",
"5fefa2556308ab102854bafc",
"5fefa2556308ab102854bag7",
"5fefa2556308ab102854bah8",
"5fefa2556308ab102854bac5",
"5fefa2556308ab102854babc"
],
"created_count": 4,
"purchased": [],
"purchased_count": 0,
},
"following": {
"users": [],
"count": 0
},
"followers": {
"users": [],
"count": 0
},
"product_picture": "xxxxxxxxx",
....................
....................
....................
"__v": 0
}
so in this document, I have 4 product id in the productLine, I want to be able to create a stage to select at random 2 of them so that in the following stage I can do the $lookup on these IDs. so basically after the stage, the document would look something like this.
{
_id: "61005f388308a717883ad3d2",
...................
...................
"productLine": {
"product": [
"5fefa2556308ab102854baf8", // this would be chosen at random
"5fefa2556308ab102854baf9", // this would be chosen at random
],
"created_count": 4,
"purchased": [],
"purchased_count": 0,
},
"following": {
"users": [],
"count": 0
},
"followers": {
"users": [],
"count": 0
},
"product_picture": "xxxxxxxxx",
....................
....................
....................
"__v": 0
}
the idea is when a user selects the product line, it will return two random product from that product line.
any help would be appreciated!!!
CodePudding user response:
You can perform the $sample
in a subpipeline of $lookup
.
{
"$lookup": {
"from": "product",
"pipeline": [
{
"$project": {
_id: 1
}
},
{
"$sample": {
"size": 4
}
}
],
"as": "productLookup"
}
}
Here is the Mongo playground for your reference.