mongoengine bulk upsert a batch of record?
我要
我想知道
如果没有,我想知道如何
1 2 3 4 5 6 7 8 9 | class User(Document): username = StringField(required=True) password = StringFiedl(required=True) meta = {'db_alias': 'user_info', 'collection': 'user', 'indexes': [{'fields': ['username'], 'unique': True}] } def save_users(self, users): Users.objects.insert(users) # raise mongoengine.errors.NotUniqueError |
实际上,您可以通过从MongoEngine使用的pymongo驱动程序访问基础集合对象来直接使用批量操作API。 从2.6版开始,MongoDB本身就支持批量操作。 自pymongo驱动程序v3以来,已有更新的方法来访问这些方法,但是自从相应的驱动程序更新到2.6 Server版本(pymongo 2.7)以来,基本方法就已经存在。
要使用MongoEngine做到这一点,您可以从您的类中调用未记录的
1 2 3 4 5 6 | bulk = Users._get_collection().initialize_ordered_bulk_op() for user in users: # where users is a list of dicts containing data to work on bulk.find({"matchField": user['matchField'] }).upsert().replace_one(user) bulk.execute() |
或您可能想要的其他任何批量方法,例如
您在这里使用的是原始python对象,因为MongoEngine本身没有直接等效的对象。 但是您可以通过从底层驱动程序访问方法来使用这些操作