2

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?

2
  • 2
    you can not access it by index, you have to use operators, $first or $arrayElemAt Commented Jun 24, 2022 at 15:19
  • 2
    $slice also works =) Commented Jun 24, 2022 at 15:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.