0

I have inserted multiple documents in my Mongo database incorrectly. I have accidentally nested the data inside another data object:

{
  "_id": "5cdfda8ddc5cf00031fd3949",
  "payload": {
    "timestamp": "2019-05-18T10:12:29.896Z",
    "data": {
      "data": {
        "name": 10,
        "age": 10,
      }
    }
  },
  "__v": 0
}

I would like the document to not have the extra data object. So I would like it to look like this:

{
  "_id": "5cdfda8ddc5cf00031fd3949",
  "payload": {
    "timestamp": "2019-05-18T10:12:29.896Z",
    "data": {
      "name": 10,
      "age": 10,

    }
  },
  "__v": 0
}

Is there a way in Mongo for me to update all the documents that have 2 data objects to just have one like shown above?

2 Answers 2

0

Alas, you cannot do this with one database request. You have to loop over all documents programmatically, set the new data and update them in the database.

1
  • That is what i taught i would have to do just taught there may have been a easier way
    – Johnjoe
    Commented May 27, 2019 at 15:35
0

You could use the aggregation framework, which won't let you update in place, but you could use the $out operator to write the results to a new collection, if that's an option.

db.collection.aggregate([
  {
    $project: {
      __v : 1,
      "payload.timestamp" : 1,
      "payload.data" : "$payload.data.data"
    },
  },
  {
    "$out": "newCollection"
  }
])

Or if you have a mixture of docs with correct format and docs with incorrect format, you can use the $cond operator to determine the correct output:

db.collection.aggregate([
  {
    $project: {
      __v : 1,
      "payload.timestamp" : 1,
      "payload.data" : {
        $cond: [
          { $ne : [ "$payload.data.data", undefined]},
          "$payload.data.data",
          "$payload.data"
        ]} 
    }
  },
  {
    "$out": "newCollection"
  }
])
2
  • 1
    Writing to another collection isnt really an option so i went with @mbuechmann suggest of looping over them and updating them
    – Johnjoe
    Commented May 27, 2019 at 15:33
  • Great! You can click the checkmark beside their answer, to accept it so that the community knows the question is solved stackoverflow.com/help/someone-answers
    – sheilak
    Commented May 27, 2019 at 15:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.