0

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.

0

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

check this link link in second document arr first value is 'e' which is not in data object. still query add field with last value maybe like "data": "data a", i want ; if arr first element not present in data object that time value will null
Thank you! for Answer i got my solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.