I am trying to get randomly one item from an array using mongoose, I use .aggregate
:
const winner = await gSchema.aggregate(
[
{ "$unwind": "$Users" },
{ "$sample": { "size": 1 } }
]
)
I console.log(winner)
I get:
[
{
_id: new ObjectId("62c0943a789817d59c19bfa4"),
Guild: '1234567889',
Host: '1234567889',
Channel: '1234567889',
MessageID: '1234567889',
Time: '86400000',
Date: 2022-07-02T18:53:46.981Z,
Users: '1234567889',
__v: 0
}
]
Instead, I want to only get the value of Users
like: 1234567889
in my console, not the whole Schema, any idea how to achieve that?
Also is there a way to use filter when using aggregate
?
2
Answers
Quick update about the issue, using
console.log(winner[0].Users)
solved my problemIn order to get only the
Users
data add a projection step:In order to filter, add a
$match
step.