Arrays and Dicts in MongoDB
Array of dictionaries becomes hard to update in MongoDB.
Array is easy to use if the elements are flat, e.g.,
{ "alternative_of_names": [ "Jane Doe", "John Doe", "Tim Doe" ] }
When updating with new values, we could simply use
$addToSet
.Array of json objects becomes really hard to update.
{ "alternative_of_names": [ { "source": "Magzine", "first": "Jane", "last": "Doe" }, { "source": "TV", "first": "John", "last": "Doe" }, { "source": "Ads", "first": "Tim", "last": "Doe" } ] }
Suppose we would like to update the name from source “Ads”, it becomes tedious.
For the above purpose, we could simply rewrite the database in the following way.
{ "alternative_of_names": { "Magzine": { "first": "Jane", "last": "Doe" }, "TV": { "first": "John", "last": "Doe" }, "Ads": { "first": "Tim", "last": "Doe" } } }
Then we can update easily with
$set
.
Planted:
by Lei Ma;
Dynamic Backlinks to
til/programming/database/mongodb-array-and-dict
:L Ma (2019). 'Arrays and Dicts in MongoDB', Datumorphism, 08 April. Available at: https://datumorphism.leima.is/til/programming/database/mongodb-array-and-dict/.