Database Reference
In-Depth Information
Now you can use the $pullAll operator to remove the multiple tags. The following example shows how to use
this operator; the example also executes a find_one() command immediately afterward to confirm that the Bacon
and Spam tags have been removed:
>>> collection.update({"Type" : "Chair"}, {"$pullAll" : {"Tags" : ["Bacon","Spam"] } },
multi = False)
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : "True"})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty']
}
Saving Documents Quickly with save()
You can use the save() function to quickly add a document through the upsert method. For this to work, you must
also define the value of the _id field. If the document you want to save already exists, it will be updated; if it does not
exist already, it will be created.
Let's look at an example that saves a document called Desktop . Begin by specifying the document by typing it into
the shell with an identifier, after which you can save it with the save() function. Executing the save() function returns
the ObjectId from the document once the save is successful:
>>> Desktop = ( {
"Status" : "In use",
"Tags" : ["Desktop","In use","Marketing","Warranty"],
"ItemNumber" : "4532FOO",
"Location" : {
"Department" : "Marketing",
"Building" : "2B",
"Desknumber" : 131131,
"Owner" : "Martin, Lisa",
}
} )
>>> collection.save(Desktop)
ObjectId('4c5ddbe24abffe0f34000001')
Now assume you realize that you forgot to specify a key/value pair in the document. You can easily add this
information to the document by defining the document's name, followed by its key between brackets, and then
including the desired contents. Once you do this, you can perform the upsert by simply saving the entire document
again; doing so returns the ObjectId again from the document:
>>> Desktop[ "Type" ] = "Desktop"
>>> collection.save(Desktop)
ObjectId('4c5ddbe24abffe0f34000001')
As you can see, the value of the ObjectId returned is unchanged.
 
Search WWH ::




Custom Search