Home > Software design >  Is it possible to access dinamically to a value from a document based on another property of the sam
Is it possible to access dinamically to a value from a document based on another property of the sam

Time:07-19

I have documents like this:

{
   "status": "in_progress",
   "statusLog": {
       "received": "2010-01-01",
       "in_progress": "2011-02-02"
   }
}

Is it possible to return something like this?

{
   "status": "in_progress"
   "date": "2011-02-02"
}

the status value could be anything... and its related date is on the same document in a property inside "statusLog" with the same value name.

I have a long aggreggate pipeline, but at the end I want to add this "date" field. I was thinking adding a $addField stage to the end of the pipeline... but I can't find any mongodb operator that I could use to achieve it.

Something like this:

collection.aggreggate([
   {
      $addFields: {
          "date": {}//What mongodb operator here?
      }
   }
])

some context... before, the status were fixed "RECEIVED", "IN_PROGRESS", "CLOSED"... And i was using this:

$addFields: {
          statusDate: {
            $switch: {
              branches: [
                {
                  case: { $eq: ['$status', 'RECEIVED'] },
                  then: { $ifNull: ['$statusLog.RECEIVED.datetime', null] },
                },
                {
                  case: { $eq: ['$status', 'IN_PROGRESS'] },
                  then: { $ifNull: ['$statusLog.IN_PROGRESS.datetime', null] },
                },
                {
                  case: { $eq: ['$status', 'CLOSED'] },
                  then: { $ifNull: ['$statusLog.CLOSED.datetime', null] },
                },
              ],
              default: null,
            },
          },
        },

But now the field value can be anything.

CodePudding user response:

Try this one:

db.collection.aggregate([
  {
    $set: {
      statusLog: {
        $filter: {
          input: { $objectToArray: "$statusLog" },
          cond: { $eq: [ "$$this.k", "$status" ] }
        }
      }
    }
  },
  {
    $project: {
      date: { $first: "$statusLog.v" },
      status: 1
    }
  }
])

Mongo Playground

  • Related