0

How to remove 'name' property? Tried chaining update with find but no luck, the syntax is not allowed.

when I run db.getCollection('myCollection').find({"key":"person"}) I got this

{
    "key" : "person",
    "value" : [ 
        {   
            id: 1
            "name" : "james",
        },
        {   
            id: 2
            "name" : "john",
        }, 
    ]
}

Why this won't work? db.getCollection('myCollection').find({"key":"person"}).update({}, {$unset: {name:1}}, {multi: true});

  • It won't work because it's not valid syntax. `find()` returns a `Cursor` object so the only things you can "chain" are ["cursor methods"](https://docs.mongodb.com/manual/reference/method/js-cursor/) like `.toArray()`. As for what you are trying to do, the `update()` takes a "query" as it's first argument, and that's your `find`. Also, you cannot update multiple array elements like that, and there's a completely different way to do it. As linked. – Neil Lunn Jun 06 '18 at 06:56
  • @Neil thanks, but I followed one of the solution and did this `db.getCollection("myCollection").find({ key: "person" }) .forEach(function (doc) { doc.value.forEach(function (v) { delete v.name; }); db.collection.save(doc); });` the records is not reflecting, although I can see correct result when I do `printjson(doc)`. Any idea what's wrong? –  Jun 06 '18 at 07:07
  • There's a lot more than "one" solution there. Go and take a real look and don't just blindly trust "top voted" or "accepted". Read them through as there are only about three which stand up as credible. In case it's not clear, the one you chose is not it. [Modern API Approach](https://stackoverflow.com/a/46054172/2313887) and [Methods for Earlier API](https://stackoverflow.com/a/33193231/2313887). And possibly even [this one](https://stackoverflow.com/a/34887428/2313887) but there are still reasons why that's not great. – Neil Lunn Jun 06 '18 at 07:09

0 Answers0