Home > database >  Mongoose getting random object from array without getting the "_id"
Mongoose getting random object from array without getting the "_id"

Time:06-18

Hello I am trying to get a random object from array with mongoose but I am getting the _id with it. I used:

let user = Schema.aggregate([
  {
    $unwind: "$Users"
  },
  {
    "$sample": {
      "size": 1
    },
    
  }
])

Output:

[
  {
    "Users": "805249193890676736",
    "_id": ObjectId("5a934e000102030405000000")
  }
]

So I am trying to get only the Users object as an output to use the User ID, is it possible?

CodePudding user response:

You can use a $project step:

let user = Schema.aggregate([
  {$unwind: "$Users"},
  {$sample: {size: 1},
  {$project: {Users: 1, _id: 0}}  
  }
])
  • Related