skip to Main Content

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


  1. Chosen as BEST ANSWER

    Quick update about the issue, using console.log(winner[0].Users) solved my problem


  2. In order to get only the Users data add a projection step:

    const winner = await gSchema.aggregate(
                            [ 
                                {$unwind: "$Users"}, 
                                {$sample: {size: 1}},
                                {$project: {Users: 1, _id:0}}
                            ]
                        )
    

    In order to filter, add a $match step.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search