Database Reference
In-Depth Information
Adding a Value to an Array with $push
The $push operator lets you add a value to an array, assuming the array exists. If the array does not exist, then it will be
created with the value specified.
Warning
If you use $push to update an existing field that isn't an array, an error message will appear.
Now you're ready to add a value to an already existing array and confirm whether all went well. First, perform
the update:
>>> collection.update({"Location.Owner" : "Anderson, Thomas"},
... {"$push" : {"Tags" : "Anderson"} }, multi = True )
Now, execute find_one() to confirm whether the update(s) went well:
>>> collection.find_one({"Location.Owner" : "Anderson, Thomas"}, fields={"Tags" : "True"})
{
u'_id': ObjectId('4c57207b4abffe0e0c000000'),
u'Tags': [u'Laptop', u'Development', u'In Use', u'Anderson']
}
Adding Multiple Values to an Array with $push and $each
The $push operator can also be used to add multiple values at once to an existing array. This can be achieved by
adding the $each modifier. Here, the same rule applies: the array must already exist, or you will receive an error. The
following example uses the $each modifier in conjunction with the $ regular expression to perform a search; this
enables you to apply a change to all matching queries:
>>> collection.update({ "Location.Owner" : re.compile("^Walker,") },
... { '$push' : { 'Tags' : { '$each' : ['Walker','Warranty'] } } } )
Next, execute find_one() to see whether all went well:
>>> collection.find_one({"Location.Owner" : re.compile("^Walker,")}, fields={"Tags" : True})
{
u'_id': ObjectId('4c57234c4abffe0e0c000002'),
u'Tags': [u'Laptop', u'Development', u'In Use', u'Walker', u'Warranty']
}
Adding a Value to an Existing Array with $addToSet
The $addToSet operator also lets you add a value to an existing array. The difference is that this method checks
whether the array already exists before attempting the update (the $push operator does not check for this condition).
 
 
Search WWH ::




Custom Search