开发者社区> 问答> 正文

我如何在MongoDB中更新此数组?

嗨,大家好,我使用mongodb和python来存储一些信息,但是我想删除* timed array 中的 2nd object ,而不是 id的第一个ID *对象。你知道我该怎么办吗?

我已经尝试了一些代码,但一无所获。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 18:55:57 356 0
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'}]}}}]
    

    回答来源:stackoverflow

    2020-03-23 18:56:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
MongoDB多数据中心的方案选型之路 立即下载
阿里云MongoDB云服务构建 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载