Skip to content

Instantly share code, notes, and snippets.

@mbalex99
Last active March 14, 2019 22:25
Show Gist options
  • Save mbalex99/870b166499e099cebd8383a214bed00c to your computer and use it in GitHub Desktop.
Save mbalex99/870b166499e099cebd8383a214bed00c to your computer and use it in GitHub Desktop.
update instructions with Ditto

Setting with a Dictionary

  1. given the document like so
{
    "_id": "abc123",
    "name": "Jesse",
    "username": "jchappell",
    "location": "New York",
    "score": 23
}
  1. Now I'd just like to update the location to "San Francisco"
myCollection.updateById("123abc", [
    "location": "San Francisco"
])
{
    "_id": "abc123",
    "name": "Jesse",
    "username": "jchappell",
    "location": "New York",
    "score": 23
}

Setting a dictonary and setting with an update instruction

Setting with a dictionary like ["location": "San Francisco"] is equivalent to giving it an an array of UpdateOperation that are of the .set case variant.

myCollection.updateById("123abc", [
    UpdateOperation.set("location", "San Francisco")
])

So let's say you want to do 3 things in 1 update command

  1. Get rid of the "name" key
  2. Change location to "Paris"
  3. Change username to "jesse_chappellXYZ"

You can do this:

let operations: [UpdateOperation] [
    .unset("name", ""),
    .set("location", "Paris"),
    .set("username", "jesse_chappellXYZ"),
]
myCollection.updateById("123abc", operations)

The document will now go from:

{
    "_id": "abc123",
    "name": "Jesse",
    "username": "jchappell",
    "location": "New York",
    "score": 23
}

to:

{
    "_id": "abc123",
    "username": "jesse_chappellXYZ",
    "location": "Paris",
    "score": 23
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment