Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $sample after filtering

Let's say I want a person to find people they're not connected with, I would do:

User.find({ _id: { $nin: req.user.connections })

However, I only want to retrieve at most 10 random documents from the return. In MongoDB, there is $sample:

{ $sample: { size: <positive integer> } }

I've never used Mongo before, so I'm unsure of how to chain these two together in order for me to retrieve 10 random people the current user is unconnected to.

like image 969
db2791 Avatar asked Sep 12 '25 20:09

db2791


1 Answers

$sample is an aggregation operator, so you need to create an aggregate pipeline that chains the two operations together:

User.aggregate([
    { $match: { _id: { $nin: req.user.connections } } },
    { $sample: { size: 10 } }
])
like image 141
JohnnyHK Avatar answered Sep 16 '25 08:09

JohnnyHK