简体   繁体   中英

Unable to create a collection through insert() in pymongo for mongodb and an attribute error

I am trying to input document into my mongodb test database in colors collection which is not there but it should create one if one not exists. My following code does not show any new collection named as "colors" and as far as I understand the tutorial I am following over these links 1 , 2 that it should create one.

The code give an AttributeError:'ObjectId' object has no attribute 'inserted_id' If I don't comment out the last two lines of the code in which I'm trying to access the ObjectId returned by the insert_one(). Please look at the tutorial to see what am I doing wrong and below is my insert code in python using pymongo. The code runs commenting out last two lines but no collection is created. I am using "Mongo Express" as GUI for mongodb to view the collections and documents. The input JSON sample was used from the internet its not my own.

    #!/usr/bin/env python
from pymongo import MongoClient
#from datetime import datetime
client = MongoClient()
db = client.test
result = db.colors.insert(
        {
         "colorsArray":[{
                        "colorName":"red",
                        "hexValue":"#f00",
                    },
                    {
                        "colorName":"green",
                        "hexValue":"#0f0"
                    },
                    {
                        "colorName":"blue",
                        "hexValue":"#00f"
                    },
                    {
                        "colorName":"cyan",
                        "hexValue":"#0ff"
                    },
                    {
                        "colorName":"magenta",
                        "hexValue":"#f0f"
                    },
                    {
                        "colorName":"yellow",
                        "hexValue":"#ff0"
                    },
                    {
                        "colorName":"black",
                        "hexValue":"#000"
                    }
         ]
     }
)
x = result.inserted_id
print x

[Solved] Update: Mongo Express was not working properly and the added collection was not appearing in GUI but after stopping mongod service and rebooting the system and then restarting the mongod service and Mongo Express solved that too.

The code give an AttributeError:'ObjectId' object has no attribute 'inserted_id'

This is because you are using the insert method which return ObjetId object and; ObjectId doesn't have attribute inserted_id . You should use the insert_one method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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