Search code examples
mongodbaggregation-frameworkpymongo

How to access nested field of an array element inside a set operation in MongoDB


I am trying to access a nested field of an array element in $set operation. I have a document like,

{
  _id: ObjectId(),
  automated: [
      {
          price: 80.0,
          currency: 'USD',
          ...otherData
      },
      {
          price: 90.0,
          currency: 'INR',
          ...otherData
      },
      {
          price: 120,
          currency: 'USD',
          ...otherData
      }
  ]
}

I want to create a finalData obj which takes some values from first element of the array.

So I tried,

mongodb.aggregate([
    {"$set": {
        "finalData" : {
            "price": "$automated.0.price",       // 0th index
            "currency": "$automated.0.currency"
        }
    }}
])

But this is not working and the result is,

{
  _id: ObjectId(),
  finalData: {
    price: [],
    currency: []
  },
  ...otherData
}

I could not find any similar examples. Does anyone know how to do this ?

Thanks in advance!

Edit:

Found a similar question. The proposed solution works,

mongodb.aggregate([
    {"$set": {
        "finalData" : {
            "price": {
                "$arrayElemAt": ["$automated.0.price", 0]       // index used here
            },
            "currency": {
                "$arrayElemAt": ["$automated.0.currency", 0]
            }
        }
    }}
])

But this doesn't feel intuitive and would be happy to know if there are any alternatives to this.


Solution

  • "$automated.0.price" syntax is used for find/update operations but not in aggregation pipeline.

    Simply use

    mongodb.aggregate([
        {"$set": {
            "finalData" : {$first: "$automated"}
        }}
    ]) 
    

    or

    mongodb.aggregate([
        {"$set": {
            "finalData" : {
               price: {$first: "$automated.price"}, 
               currency: {$first: "$automated.currency"}
        }}
    ])