简体   繁体   中英

how can i update this array in MongoDB?

hi guys i'm using mongodb with python for storing some information but i want to delete the 2nd object in the timed array in the 1st ID object without touching the second id object. Do you know how can i do?

有数据库的样子

I have already tried with some code but nothing.

You can try using $unset and $pull to remove that array element.

Something like this works:

from pymongo import MongoClient
from bson.objectid import ObjectId
import pprint

client = MongoClient()
db = client['test']
collection = db.sotest1

a = list(collection.find({'_id': ObjectId('5e6d9cb1e61607439cf2416f')}))
print('Before Update')
pprint.pprint(a)

#  Remove by Index using unset and pull
collection.update_one({'_id': ObjectId('5e6d9cb1e61607439cf2416f')},
                      {'$unset': {'timed.576819964179382272.timed.1': 1}})
collection.update_one({'_id': ObjectId('5e6d9cb1e61607439cf2416f')},
                      {'$pull': {'timed.576819964179382272.timed': None}})

a = list(collection.find({'_id': ObjectId('5e6d9cb1e61607439cf2416f')}))
print('After update')
pprint.pprint(a)

Results:

Before Update
[{'_id': ObjectId('5e6d9cb1e61607439cf2416f'),
  'timed': {'173569203977060353': {'name': 'Pollig#4963',
                                   'timed': [{'strObj': 'stuff in here'}]},
            '576819964179382272': {'name': 'Ranka#9895',
                                   'timed': [{'str1': 'test'},
                                             {'str1': 'remove me'},
                                             {'str2': 'test3'},
                                             {'extra': 'extra object in '
                                                       'array'}]}}}]
After update
[{'_id': ObjectId('5e6d9cb1e61607439cf2416f'),
  'timed': {'173569203977060353': {'name': 'Pollig#4963',
                                   'timed': [{'strObj': 'stuff in here'}]},
            '576819964179382272': {'name': 'Ranka#9895',
                                   'timed': [{'str1': 'test'},
                                             {'str2': 'test3'},
                                             {'extra': 'extra object in '
                                                       'array'}]}}}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM