問題描述
如何刪除 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 Drews、Belly Buster)