【问题标题】:how can i update this array in MongoDB?如何在 MongoDB 中更新此数组?
【发布时间】:2020-03-15 02:39:44
【问题描述】:

大家好,我正在使用 mongodb 和 python 来存储一些信息,但我想删除 第一个 ID 中 定时数组 中的 第二个对象 /strong> 对象而不触及第二个 id 对象。你知道我该怎么做吗?

我已经尝试了一些代码,但没有。

【问题讨论】:

  • 请分享您尝试过的内容,以及您正在使用的库。
  • 请不要粘贴图片。请改用格式化文本。
  • 对不起,图片是图书馆 si pymongo

标签: python arrays json python-3.x mongodb


【解决方案1】:

您可以尝试使用$unset$pull 删除该数组元素。

这样的工作:

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)

结果:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多