skip to Main Content

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.

2

Answers


  1. 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}.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search