Home

Tags

MongoDB array, операции с массивами

2011-04-16 mongodb python array

Обновление атрибута в массиве

t.save({'title':'ABC', 'comments':[ {'user':'jon', 'votes':1}, \
    {'user':'bil', 'votes':3} ]})
t.update({'comments.user':'jon' }, {'$inc':{'comments.$.votes':1}}, False, True)
print t.find_one()
Результат
 {u'_id': ObjectId('4da9d1069f1fdf1702000000'), u'comments':[
{u'votes': 2, u'user': u'jon'}, {u'votes': 3, u'user': u'bil'}
], u'title': u'ABC'}


Добавить/убрать из множества (set)
t.save({ 'tags':['linux','mac'] })
t.update({},{ '$addToSet':{ 'tags':'windows' } })
print t.find_one()
t.update({},{ '$pull':{ 'tags':'windows' } })
print t.find_one()
Результат
{u'_id': ObjectId('4da9d6b99f1fdf1941000001'), u'tags': [u'linux', u'mac', u'windows']}
{u'_id': ObjectId('4da9d6b99f1fdf1941000001'), u'tags': [u'linux', u'mac']}


Добавить/убрать из массива
t.save({ 'dim':[1,2] })
t.update({},{ '$push':{ 'dim':3 } })
print 'push',t.find_one()
t.update({},{ '$pushAll':{ 'dim':[4,5] } })
print 'pushAll',t.find_one()
t.update({},{ '$pull':{ 'dim':3 } })
print 'pull',t.find_one()
t.update({},{ '$pop':{ 'dim':1 } })
print 'pop',t.find_one()
t.update({},{ '$pop':{ 'dim':-1 } })
print 'pop',t.find_one()
Результат
push {u'dim': [1, 2, 3], u'_id': ObjectId('4da9d95a9f1fdf1ab1000002')}
pushAll {u'dim': [1, 2, 3, 4, 5], u'_id': ObjectId('4da9d95a9f1fdf1ab1000002')}
pull {u'dim': [1, 2, 4, 5], u'_id': ObjectId('4da9d95a9f1fdf1ab1000002')}
pop {u'dim': [1, 2, 4], u'_id': ObjectId('4da9d95a9f1fdf1ab1000002')}
pop {u'dim': [2, 4], u'_id': ObjectId('4da9d95a9f1fdf1ab1000002')}