Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo: How to insert an array of multiple fields in a document?

I am working on MongoDB in python [pymongo]. I want to insert an array of multiple fields in a document. For example: In the below structure of a collection, I want to insert array of Places Visited in all documents. I do not know what it is called in the world of Mongo.So that I may insert it. How to insert an array in a document? Can some one help?

collectionName
    {
            "_id" : "4564345343",
            "name": "Bunty",
            "Basic Intro": "A.B.C.D.",
            "Places Visited": [
                    "1" : "Palace of Dob",
                    "2" : "Palace of Victoria",
                    "3" : "Sahara Desert"
            ]
    }
    {
            "_id"  : "45657865745",
            "name": "Humty",
            "Basic Intro": "B.C.D.",
            "Places Visited": [
                    "1" : "Palace of Pakistan",
                    "2" : "Palace of U.S.A."
                    "3" : "White House"
            ]
    }
like image 551
Amar Avatar asked Dec 28 '25 07:12

Amar


1 Answers

This should give you the idea how to do it

import pymongo

client = pymongo.MongoClient('yourHost', 30000) # adjust to your needs
db = client.so
coll = db.yourcollection

# show initial data
for doc in coll.find():
    print(doc)

# update data
places_visited = [
    "Palace of Dob",
    "Palace of Victoria",
    "Sahara Desert"
]
coll.update({}, { "$set": { "Places Visited": places_visited } }, multi=True)

# show updated data
for doc in coll.find():
    print(doc)  

which for your sample data should give output similar to this

daxaholic$ python3 main.py 
{'name': 'Bunty', 'Basic Intro': 'A.B.C.D.', '_id': '4564345343'}
{'name': 'Humty', 'Basic Intro': 'B.C.D.', '_id': '45657865745'}
{'name': 'Bunty', 'Places Visited': ['Palace of Dob', 'Palace of Victoria', 'Sahara Desert'], 'Basic Intro': 'A.B.C.D.', '_id': '4564345343'}
{'name': 'Humty', 'Places Visited': ['Palace of Dob', 'Palace of Victoria', 'Sahara Desert'], 'Basic Intro': 'B.C.D.', '_id': '45657865745'}  

For further information see the docs about update

like image 80
DAXaholic Avatar answered Dec 30 '25 22:12

DAXaholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!