Search code examples
mongodbmongoose

Is there a way to change a field from an array to a single element in a mongodb query


I am trying to query my DB on a collection but I have some field that I would like to change from an array of objects to a single object that have been picked up randomly from the array. is this possible to do this in a query?

Here is the structure of my document:

{
  "_id": 
  "Field": [
    {
      Element1_Text1: "",
      Element1_Text2: ""
    },
    {
      Element2_Text1: "",
      Element2_Text2: ""
    }
  ]
}

Here is what I am expecting to get.

{
  "_id": 
  "Field": [
    {
      Element1_Text1: "",
      Element1_Text2: ""
    }
  ]
}

or

{
  "_id": 
  "Field": [
    {
      Element2_Text1: "",
      Element2_Text2: ""
    }
  ]
}

Solution

  • Not sure of any direct way of doing this in mongodb, simple thing is to do an aggregate query with stage $unwind and $sample.

    db.collection.aggregate([
      {
        $unwind: "$Field"
      },
      {
        $sample: {
        size: 1
      }
     }
    ])