Monday, August 18, 2014

Creating, Updating, and Deleting Documents

Creating, Updating, and Deleting Documents

Inserting and saving documents

Use the collection's insert method

> db.foo.insert({"bar" : "baz"})

Removing Documents

> db.users.remove()

Also takes a query document as a parameter

> db.users.remove({"user" : "jones"})

> db.users.drop()

Updating Documents

The last update wins.

Document Replacement

To convert the following
{
    "_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
    "name" : "joe",
    "friends" : 32,
    "enemies" : 2
}

to
{
    "_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
    "username" : "joe",
    "relationships" :
    {
        "friends" : 32,
        "enemies" : 2
    }
}

> var joe = db.users.findOne({"name" : "joe"});
> joe.relationships = {"friends" : joe.friends, "enemies" : joe.enemies};
{
    "friends" : 32,
    "enemies" : 2
}
> joe.username = joe.name;
"joe"
> delete joe.friends;
true
> delete joe.enemies;
true
> delete joe.name;
true
> db.users.update({"name" : "joe"}, joe);

Using Modifiers

Partial updates can be done extremely efficiently by using atomic update modifiers.
Update modifiers can specify complex update operations such as
  • altering
  • adding
  • removing keys
  • manipulating arrays and embedded documents

$set
"$set" sets the value of a key. If the key does not yet exist, it will be created

Creating a new key in a document
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin"
}
> db.users.update({"_id" : ObjectId("4b253b067525f35f94b60a31")},
... {"$set" : {"favorite book" : "war and peace"}})
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin",
"favorite book" : "war and peace"
}

Updating the value of an existing key in a document
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" : "green eggs and ham"}})

Updating the value of an existing key to an array in a document
db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" :
... ["cat's cradle", "foundation trilogy", "ender's game"]}})

To remove a key
db.users.update({"name" : "joe"},
... {"$unset" : {"favorite book" : 1}})

Changing an embedded document
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"title" : "A Blog Post",
"content" : "...",
"author" : {
"name" : "joe",
"email" : "joe@example.com"
}
}
> db.blog.posts.update({"author.name" : "joe"}, {"$set" : {"author.name" : "joe schmoe"}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"title" : "A Blog Post",
"content" : "...",
"author" : {
"name" : "joe schmoe",
"email" : "joe@example.com"
}
}

$inc
The "$inc" modifier can be used to
  • change the value for an existing key or 
  • to create a new key if it does not already exist

Creating a new key in a document
> db.games.insert({"game" : "pinball", "user" : "joe"})
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 50}})
> db.games.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 50
}

Increasing value of an existing key
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 10000}})
> db.games.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 10050
}

$push

adds an element to the end of an array if the key exists
creates a new array if it does not

> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "..."
}
> db.blog.posts.update({"title" : "A blog post"},
  {$push : {"comments" : {"name" : "joe", "email" : "joe@example.com", "content" : "nice post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
}
]
}

To add another comment, use $push again

> db.blog.posts.update({"title" : "A blog post"},
   {$push : {"comments" : {"name" : "bob", "email" : "bob@example.com", "content" : "good post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
},
{
"name" : "bob",
"email" : "bob@example.com",
"content" : "good post."
}
]
}

Adding a value to an array only if it is not present
> db.papers.update({"authors cited" : {"$ne" : "Richie"}},
... {$push : {"authors cited" : "Richie"}})

$addToSet

Use $addToSet to prevent duplicates

> db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"username" : "joe",
"emails" : [
"joe@example.com",
"joe@gmail.com",
"joe@yahoo.com"
]
}
> db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
... {"$addToSet" : {"emails" : "joe@gmail.com"}})
> db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"username" : "joe",
"emails" : [
"joe@example.com",
"joe@gmail.com",
"joe@yahoo.com",
]
}

$addToSet with $each
to add multiple unique values
> db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
{"$addToSet" : {"emails" : {"$each" : ["joe@php.net", "joe@example.com", "joe@python.org"]}}})

$pop
{$pop : {key : 1}} removes an element from the end of the array.
{$pop : {key : -1}} removes it from the beginning

$pull
"$pull" is used to remove elements of an array that match the given criteria.
> db.lists.insert({"todo" : ["dishes", "laundry", "dry cleaning"]})
> db.lists.update({}, {"$pull" : {"todo" : "laundry"}})
> db.lists.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"todo" : [
"dishes",
"dry cleaning"
]
}

Positional array modifications
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b329a216cc613d5ee930192"),
"content" : "...",
"comments" : [
        {
                "comment" : "good post",
                "author" : "John",
                "votes" : 0
        },
        {
                "comment" : "i thought it was too short",
                "author" : "Claire",
                "votes" : 3
        },
        {
                "comment" : "free watches",
                "author" : "Alice",
                "votes" : -1
        }
    ]
}

> db.blog.update({"post" : post_id},
... {"$inc" : {"comments.0.votes" : 1}})

We don’t know what index of the array to modify without querying for the document first and examining it.
MongoDB has a positional operator, "$", that figures out which element of the array the query document
matched and updates that element.

db.blog.update({"comments.author" : "John"},
... {"$set" : {"comments.$.author" : "Jim"}})

Upserts

An upsert is a special type of update

If no document is found that matches the update criteria, a new document will be created by combining the criteria and update documents.

If a matching document is found, it will be updated normally.

Benefits:
  • We avoid making a round-trip to the database
  • We also avoid a race condition where more than a document can be inserted for a given URL.
> db.math.remove()
> db.math.update({"count" : 25}, {"$inc" : {"count" : 3}}, true)
> db.math.findOne()
{
     "_id" : ObjectId("4b3295f26cc613d5ee93018f"),
     "count" : 28
}

The upsert creates a new document with a "count" of 25 and then increments that by 3, giving us a document
where "count" is 28.

Updating Multiple Documents

Updates, by default, update only the first document found that matches the criteria
To modify all of the documents matching the criteria, you can pass true as the fourth parameter to update

> db.users.update({birthday : "10/13/1978"},
... {$set : {gift : "Happy Birthday!"}}, false, true)

getLastError

To see the number of documents updated by a multiple update
The "n" key will contain the number of documents affected by the update

> db.runCommand({getLastError : 1})
{
     "err" : null,
     "updatedExisting" : true,
     "n" : 5,
     "ok" : true
}

Update generic interface

<collection instance>.update(<query document>,   , <is an upsert? i.e. should insert and update>, <should update multiple documents>)

Returning Updated Documents







No comments:

Post a Comment