[Fixed] MongoDB query to remove a key of an Object in my database

Issue

So, basically I’m trying to make an API Restful (just for studies purposes) with:

NodeJS, Express and MongoDB

I already have my database set up, but I need to delete a Key from an Object.

If I send a request GET in my messages endpoint, this will return:

[
    {
        "_id": "5f9b1e0186a911001714dd3c",
        "texto": "será se vai ?"
    },
    {
        "_id": "604fd3859b2fd50017027472",
        "texto": "salve rapaziada esse aqui é o texto que eu to colocando"
    },
    {
        "_id": "604fd4389b2fd50017027474",
        "texto": "Mensagem editada aAa",
        "mensagem": ""
    }
]

The text is in PT-BR

The key mensagem was a misstake, but now I wanna know how to resolve.

So, I wanna delete mensagem key, the third object.

I’m using NoSqlBooster, but if someone use Mongo Compass, I need to know too.

Solution

$unset

update

unset will remove the key from the collection and passing true at the end of the update method is a flag set to `update multiple records.

db.collectionName.update({}, { $unset: { mensagem:1 } }, { multi: true });

Leave a Reply

(*) Required, Your email will not be published