简体   繁体   English

为每个创建mongoDB集合

[英]Create mongoDB collection for each

I wish to create a collection in MongoDB based on an ID. 我希望基于ID在MongoDB中创建一个集合。 Each ID should get its own collection. 每个ID都应拥有自己的集合。 I tried to add the id to collection = db.id to create a new collection if one is not already there, but it doesn't work. 我尝试将id添加到collection = db.id中,以创建一个新集合(如果尚不存在),但是它不起作用。 This just creates a collection called id. 这只会创建一个名为id的集合。

 import pymongo as pm

    list = [{'id':'1', 'fruit':'apple', 'drink':'juice'},
             {'id':'2', 'fruit':'pear', 'drink':'coffee'},
             {'id':'2', 'fruit':'banana', 'drink':'milk'}, 
             {'id':'2', 'fruit':'banana', 'drink':'fanta'},
             {'id':'3', 'fruit':'mango', 'drink':'tea'},
             {'id':'1', 'fruit':'kiwi', 'drink':'cola'}]


    for item in list:
        id = item['id']

        client = pm.MongoClient("X")
        db = client.fruit_n_drink
        collection = db.id
        x = collection.insert_one(w)

db.id is like db['id'] . db.id就像db['id'] You want to use db[id] . 您要使用db[id]

That said, it is also going to fail, because your IDs won't work with MongoDB's naming restrictions described in https://docs.mongodb.com/manual/reference/limits/#Restriction-on-Collection-Names 就是说,它也会失败,因为您的ID将无法使用https://docs.mongodb.com/manual/reference/limits/#Restriction-on-Collection-Names中描述的MongoDB的命名限制

Edit 编辑

Reading more carefully, I think that my previous statement about the documentation is not true: looks like not starting with a character number character is just a recommendation, not a restriction. 仔细阅读后,我认为我先前关于文档的陈述是不正确的:似乎不以字符数字开头只是一个建议,而不是一个限制。

从pymongo

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

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