Home > other >  mongodb add field in all documents derived from another field
mongodb add field in all documents derived from another field

Time:04-07

here is my data which I need to add in a collection

let data = {
    'a':'data a',
    'ab':'data a',
    'b':'data b',
    'c':'data c'
}

here is my collection data:

{
    name:'xyz',
    age:'100',
    arr: ['a','ab']
}

what I want:

{
    name:'xyz',
    age:'100',
    arr: ['a','ab'],
    data:'data a' //get this from arr first element, and that is key in data object that's value here 
}

can someone help me to write this query to add new field in all documents ?

here is get query for same But, this time I want to insert data in all documents.

CodePudding user response:

db.collection.update({},
[
  {
    $set: {
      data: {
        $objectToArray: {
          "a": "data a",
          "ab": "data a",
          "b": "data b",
          "c": "data c"
        }
      }
    }
  },
  {
    $set: {
      index: { $indexOfArray: [ "$data.k", { $first: "$arr" } ] }
    }
  },
  {
    $set: {
      data: {
        $cond: {
          if: { $eq: [ "$index", -1 ] },
          then: null,
          else: { $arrayElemAt: [ "$data.v", "$index" ] }
        }
      }
    }
  },
  {
    $unset: "index"
  }
],
{
  multi: true
})

mongoplayground

CodePudding user response:

you can add aggregation query in update only.

db.collection.update({},[
  {
    '$addFields': {
      'data': {
        '$objectToArray': {
          'a': 'data a', 
          'ab': 'data a', 
          'b': 'data b', 
          'c': 'data c'
        }
      }
    }
  }, {
    '$addFields': {
      'data': {
        '$arrayElemAt': [
          '$data.v', {
            '$indexOfArray': [
              '$data.k', {
                '$first': '$arr'
              }
            ]
          }
        ]
      }
    }
  }
], {multi:true})

if you need to update multiple documents then you have to pass {multi:true}.

  • Related