简体   繁体   English

我如何在 MongoDB 中更新这个数组?

[英]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.大家好,我正在使用 mongodb 和 python 来存储一些信息,但我想删除一个 ID对象中定时数组中的第二个对象,而不触及第二个 id 对象。 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.您可以尝试使用$unset$pull来删除该数组元素。

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'}]}}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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