$addfields add a field based on condition on array value of document

Hi, In my document I have an array field containing objects. I would like to use “$addfield” to add a new field to the document by checking for the value contained in the object array in the document. For example:
{ oid:1,
ck:[{tag:“A”,
dtime:“2022-04-01”},
{“tag”:“B”,
dtime:“2022-04-03”}
]
}
In this document, I would like to use “$addfield” and add new field “pickdate” if the document contains “$ck.tag” as “A”.

{
oid:1,
ck:[{tag:“A”,
dtime:“2022-04-01”},
{“tag”:“B”,
dtime:“2022-04-03”}
]
“pickdate”:“2022-04-01”
}

Hi @Yogalakshmi_J ,

You will need an aggregation like the following:

db.collection.aggregate([{
 $addFields: {
  pickdate: {
   $filter: {
    input: '$ck',
    as: 'tag',
    cond: {
     $eq: [
      '$$tag.tag',
      'A'
     ]
    }
   }
  }
 }
}, {
 $addFields: {
  pickdate: '$pickdate.dtime'
 }
}])

If you need just the first value found do:

[{
 $addFields: {
  pickdate: {
   $filter: {
    input: '$ck',
    as: 'tag',
    cond: {
     $eq: [
      '$$tag.tag',
      'A'
     ]
    }
   }
  }
 }
}, {
 $addFields: {
  pickdate: {$first : '$pickdate.dtime' }
 }
}]

Thanks
Pavel

1 Like