Paul

Python 3 with MongoDB – Part Two

In the first part of this tutorial we installed pymongo , connected to the database, created a collection, inserted a few documents and then retrieved the documents back out of MongoDB. In this tutorial we’ll go through updating a document and deleting a document.

Different ways to create and update

Save

Save will perform an insert if the _id field doesn’t match an existing _id or is missing (mongodb will create an id automatically if it’s left out). If an existing _id is supplied then the document will be updated.

db.collection.save({"name":"paul","job":"programmer"})

The above will create a new document

db.collection.save({"name":"john",_id:123})

This will update the document for john if a document with _id of 123 already exists

Update

Update is the default method of modifying a document. By default it updates one document but it can affect multiple documents with the ‘multi’ option. The format of update is:

db.collection.update( <query>, <change>, <options> )

query is similar to where in sql (what you are effecting)
change is similar to set in sql (what effect to perform)

There are several commands to update documents in MongoDB. I’ve listed some of them below.

  • $set Set field to a new value
  • $unset Remove a field from the document
  • $push Add a value into the array in the document
  • $pushAll Add several values onto the array
  • $addToSet Add a value to an array if and only if it does not already exist
  • $pop Remove the last value of an array
  • $pull Remove all occurrences of a value from an array
  • $rename Rename a field

Example of set

db.collection.update({_id:123},{‘$set’:{‘name’:’joe’}})

Deleting a document

To delete a document use the ‘remove’ command.

db.collection.remove( <query>, <justOne> )
  • query is similar to where in a sql command
  • justOne takes a boolean and if true limits the deleting to 1 document

If you use remove with no query then it deletes all documents in the collection.

db.mycollection.remove('name':'Paul')

The above will remove all documents with the field ‘name’ set to ‘Paul’

 

There is a lot more to MongoDB and there is plenty of documentation at http://docs.mongodb.org/manual/contents/

 

Leave a Reply

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close