'How to remove an element within a field in MongoDB
{
_id: "d473ad718f214f158b31d591a97a5ce7",
name: 'sam',
keys: {
q8f3ff57b03940959e1ae4dfe2cb57ad: {
serviceaccountkey: {
keyID: 'q8f3ff57b03940959e1ae4dfe2cb57ad',
status: 'ACTIVE',
keytype: 2,
}
},
m887f7854adb4907b57903b896bcf6d6: {
serviceaccountkey: {
keyID: 'm887f7854adb4907b57903b896bcf6d6',
status: 'ACTIVE',
keytype: 2,
}
}
}
}
}
Suppose this is a document. How do I remove the first key, with ID "q8f3ff57b03940959e1ae4dfe2cb57ad" from this document? I want the end result to look like:
{
_id: "d473ad718f214f158b31d591a97a5ce7",
name: 'sam',
keys: {
m887f7854adb4907b57903b896bcf6d6: {
serviceaccountkey: {
keyID: 'm887f7854adb4907b57903b896bcf6d6',
status: 'ACTIVE',
keytype: 2,
}
}
}
}
}
Solution 1:[1]
Use $unset:
db.collection.update({},
{
"$unset": {
"keys.q8f3ff57b03940959e1ae4dfe2cb57ad": ""
}
})
Solution 2:[2]
This should do if you have many documents matching that ID or key
db.collection.updateMany({},{"$unset":{"keys.q8f3ff57b03940959e1ae4dfe2cb57ad":1}})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akhmad Zaki |
| Solution 2 | Young Emil |
