-1

When creating a Mongo Collection, I mistakenly set one of the fields equal to a string array. I now need to go back and change all of these arrays into simple strings. I had tried to first delete the field containing the string array using the below:

db.messages.update(
    {},
    { 
        '$unset': {"userResponse":1}
    },
    {'multi': true}
)

But this only set the field equal to an empty array (not deleting the field completely as hoped). Any suggestions?

Ahmed Haque
  • 7,174
  • 6
  • 26
  • 33
  • 1
    See [**`$pull`**](http://docs.mongodb.org/manual/reference/operator/update/pull/) – Blakes Seven Aug 05 '15 at 04:54
  • possible duplicate of [How to remove array element in mongodb?](http://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) – Blakes Seven Aug 05 '15 at 04:55
  • @BlakesSeven, I might be doing something wrong. But I don't think its the same question. It seems that in that question, they were looking to delete an individual element from the array. I'm looking to delete the whole array. I just tried the solution and I'm still left with a blank array in the collection. – Ahmed Haque Aug 05 '15 at 05:02

2 Answers2

2

Are you sure? Works fine for me:

> db.foos.insert({ arr: ["string"] })
WriteResult({ "nInserted" : 1 })
> db.foos.insert({ arr: ["string"] })
WriteResult({ "nInserted" : 1 })
> db.foos.update({}, { $unset: { arr: "" } }, { multi: true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.foos
test.foos
> db.foos.find()
{ "_id" : ObjectId("55c19683d66df2af820a8c74") }
{ "_id" : ObjectId("55c19685d66df2af820a8c75") }
Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
lyjackal
  • 3,984
  • 1
  • 12
  • 25
  • Strange. I just tried again and still seeing a blank array. Will continue tinkering with it. Thanks for the sanity check. – Ahmed Haque Aug 05 '15 at 05:03
  • 1
    for reference, my `db.version()` is `3.0.4` – lyjackal Aug 05 '15 at 05:10
  • I found out the issue I was facing was Mongoose related not MongoDB. In MongoDB my records were in fact getting deleted, but because my Mongoose Schema wasn't updated, the arrays were stayign in place. Thanks for the help. – Ahmed Haque Aug 05 '15 at 05:14
0

Ah. Found out my issue is Mongoose caused -- not MongoDB. The db is correct in the shell, but when viewed via the Express router the Mongoose Schema was taking control. Just needed to correct my Mongoose schema and push the code.

Ahmed Haque
  • 7,174
  • 6
  • 26
  • 33