Search code examples
mongodbpymongo

MongoDB projection - take first element from Array


My field "Field1.Field2" is an array and I want to take only first element of this array, i.e. "Field1.Field2.0" and from this I want to take any other given field for example: "Field1.Field2.0.Field3". Unfortunately when I use this projection in PyMongo then it doesn't work (this "0" make problems). The projection doesn't throw an error but the field "0" doesnt contain any values after projection while it contain the values before projection. What may be the reason?


Solution

  • Option 1:aggregation/$arrayAt or $first

    db.collection.aggregate([
    {
      $addFields: {
         x: {
          "$arrayElemAt": [
            "$x",
            0
           ]
         }
       }
     }
    ])
    

    Playground 1

    Option 2:aggregation/$slice

    db.collection.aggregate([
    {
     $addFields: {
      x: {
        "$slice": [
          "$x",
          1
        ]
       }
      }
     }
    ])
    

    Playground 2

    Option 3:find/project/$slice

    db.collection.find({},
    {
      x: {
        $slice: 1
      }
    })
    

    Playground 3