简体   繁体   English

MongoDB ObjectID被添加到python中的类属性字典

[英]MongoDB ObjectID gets added to class property dictionary in python

class Portfolio:

    def read(self, pathfilename):
        .... stuff .... 
        self.portfolio[comp_symbol] = {'name': comp_name , 'holdings': comp_holdings}



    def save_portfolio(self, port_collection):
        port_collection.insert(self.portfolio)


    def list_tickers(self):
        return (self.portfolio.keys())

    def __init__(self):
            self.portfolio = {}
            self.id = None  

Here is how to call it: 调用方法如下:

    port = Portfolio()
    print "==================================================================================="
    print port.id
    print port.portfolio
    print "==================================================================================="

    port.read(portfolio_file)
    print port.id
    print port.portfolio
    print port.portfolio.keys()
    print "==================================================================================="

    print port.list_tickers()   
    port.save_portfolio(port_collection)
    print port.list_tickers()
    print port.portfolio

The problem is that on performing the insert with pymongo, the property called portfolio changes, and there is an extra key added. 问题在于,使用pymongo执行插入操作时,名为Portfolio的属性会发生变化,并且添加了额外的键。 For example: print port.list_tickers() is different before and after the insert procedure and I do not see why this should be the case. 例如:在插入过程前后, print port.list_tickers()有所不同,我不明白为什么会这样。 Before the insert, I get ['CSCO', 'RSA', 'ARO'] and after the insert, I get: ['CSCO', 'RSA', '_id', 'ARO'] , but I should still be reading from the same class property. 在插入之前,我得到['CSCO', 'RSA', 'ARO'] ,在插入之后,我得到: ['CSCO', 'RSA', '_id', 'ARO'] _ ['CSCO', 'RSA', '_id', 'ARO'] ,但是我仍然应该从同一个类的属性读取。 The additional _id is obviously the id from MongoDB. 显然,额外的_id是来自MongoDB的ID。

The _id attribute is mandatory for records in MongoDB - it serves as the unique identifier for a record. _id属性对于MongoDB中的记录是必需的-它用作记录的唯一标识符。 MongoDB will create this automatically upon insertion of new records. MongoDB将在插入新记录时自动创建此文件。 There is no way to avoid its inclusion in the keys. 无法避免将其包含在密钥中。 However, since it's guaranteed to be in each record, you could safely pop it from the list if it really irritates you. 但是,由于可以保证每条记录中都有该记录,因此,如果确实有问题,可以从列表中安全弹出它。

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

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