leoce
leoce

Reputation: 735

mongodb remove field $unset not functioning to modify

The first answer google returned is: How do I remove a field completely from Mongo?

And the documentation: https://docs.mongodb.com/manual/reference/operator/update/unset/

I tried:

db.amazon_rev.update({}, {$unset: {'meta.asin': true}}, false, true)
db.amazon_rev.update({}, {$unset: {'meta.asin':1}}, false, true)
db.amazon_rev.update({}, {$unset: {'meta.asin': ''}}, false, true)
db.amazon_rev.update({}, {$unset: {'meta.asin': ''}}, {multi: true})
db.amazon_rev.update({}, {$unset: {'meta.asin':1}}, {multi: true})
db.amazon_rev.update({}, {$unset: {'meta.asin': true}}, {multi: true})

Every time it says:

WriteResult({ "nMatched" : 237199, "nUpserted" : 0, "nModified" : 0 })

and nothing changed:

(This collection was merged together from two collections (review and meta, both indexed by asin) by mongodb aggregation $lookup)

db.amazon_rev.findOne()
{
    "_id" : ObjectId("57f21916672286a104572738"),
    "reviewerID" : "A2E2I6B878????",
    "asin" : "B000GI????",
    "reviewerName" : "Big????",
    "helpful" : [
        0,
        0
    ],
    "unixReviewTime" : 137???????,
    "reviewText" : "........................................",
    "overall" : 5,
    "reviewTime" : "????, 2013",
    "summary" : "............",
    "meta" : [
        {
            "_id" : ObjectId("57f218e2672286a10456af7d"),
            "asin" : "B000GI????",
            "categories" : [
                [
                    ".................."
                ]
            ]
        }
    ]
}

Is there something I missed? Thanks for any suggestion!

Upvotes: 3

Views: 5208

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

Can try using positional operator $ and check that field exist or not using $exists. this process only unset the first element of an array.

db.amazon_rev.update({
   "meta.asin": {$exists: true}
},{
   $unset: {
      "meta.$.asin" : true
   }
},false,true);

if you want to delete each asin from meta array then better process is find documents and remove each meta.asin then save again that document.

Upvotes: 3

Related Questions