如何刪除 mongodb 和 pymogo 上的子文檔 (How to delete a subdocument on mongodb and pymogo)


問題描述

如何刪除 mongodb 和 pymogo 上的子文檔 (How to delete a subdocument on mongodb and pymogo)

大家好,我在使用 MongoDB 中的某些數組時遇到了一些問題。

我正在嘗試從收集代理中刪除帶有 {name:"projeto1"} 的子文檔。

有辦法訪問並刪除嗎?

from pprint import pprint
from pymongo import MongoClient
from pymongo import ReturnDocument
from bson.objectid import ObjectId
import json
import jsonpickle
from bson import json_util

class GetAgents:
    def __init__(self):
        self.client = MongoClient('localhost',27017)
        self.db = self.client['mindnet'] #nome do banco
        self.collection_agents = self.db['AGENTS'] #nome da coleção


    def create_backup(self):
        self.collection_backup = self.db['BACKUP'] #nome da coleção
        all_agents = self.collection_agents.find({})
        a = list(all_agents)
        self.collection_backup.insert_many(a)

    def remove_session(self, _agente, _projeto):




agent = GetAgents()
try:
    agent.create_backup()
    agent.remove_session('agente1','projeto2')
except:
    agent.remove_session('agente1', 'projeto2')

這就是數據庫現在的工作方式,我想按名稱刪除


參考解法

方法 1:

You need the pop command to remove a list element.

Try this example

import pymongo

db = pymongo.MongoClient()['mydatabase']
db.doc.insert_one({'name': 'a',
                   'sessions': [{'model': 0},
                                {'model': 1},
                                {'model': 2}]})

doc = db.doc.find_one({'name': 'a'}, {'_id': 0})
print(doc)
doc['sessions'].pop(1)
db.doc.replace_one({'name': 'a'}, doc, upsert=True)
doc = db.doc.find_one({'name': 'a'}, {'_id': 0})
print(doc)

gives:

{'name': 'a', 'sessions': [{'model': 0}, {'model': 1}, {'model': 2}]}
{'name': 'a', 'sessions': [{'model': 0}, {'model': 2}]}

(by Alysson DrewsBelly Buster)

參考文件

  1. How to delete a subdocument on mongodb and pymogo (CC BY‑SA 2.5/3.0/4.0)

#pymongo #Python #mongoDB #Database






相關問題

InvalidDocument:無法編碼對象:<pymongo.cursor.Cursor 對象位於 (InvalidDocument: Cannot encode object: <pymongo.cursor.Cursor object at)

為什麼 PyMongo 將 uuid.uuid1() 編碼為 BSON::Binary? (Why does PyMongo encode uuid.uuid1() as a BSON::Binary?)

一起使用 MongoEngine 和 PyMongo (Use MongoEngine and PyMongo together)

從 mongoDB 中提取信息 (Extracting information from mongoDB)

Pymongo, truy vấn tổng hợp nào trong số các truy vấn tổng hợp này sẽ hoạt động tốt hơn (Pymongo, which of these aggregare query will perform better)

查詢嵌入列表中的數組 (Querying for array in embedded list)

使用pymongo在mongodb中多次查詢單個字段的執行速度 (Querying single field multiple times execution speed in mongodb using pymongo)

使用 pymongo 用 CSV 數據更新 mongodb (update mongodb with CSV data using pymongo)

如何刪除 mongodb 和 pymogo 上的子文檔 (How to delete a subdocument on mongodb and pymogo)

有沒有辦法在 MongoDB 的一個語句中添加遞增的 id? (Is there a way to add an incrementing id in one statement in MongoDB?)

刪除文檔中的父對象 (Remove parent object in document)

MongoDB:跨文檔列表中的項目不同 (MongoDB: distinct of items inside a list across documents)







留言討論