Pymongo: How to insert an array of multiple fields in a document?
<p>I am working on <code>MongoDB</code> in <code>python</code> <code>[pymongo]</code>. 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 <code>Places Visited</code> in all documents. I do not know what it is called in the world of <code>Mongo</code>.So that I may insert it. <strong>How to insert an array in a document?</strong> Can some one help?    </p>

<pre><code>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"
            ]
    }
</code></pre>

<p>This should give you the idea how to do it  </p>

<pre><code>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)  
</code></pre>

<p>which for your sample data should give output similar to this  </p>

<pre class="lang-none prettyprint-override"><code>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'}  
</code></pre>

<p>For further information see the <a href="https://docs.mongodb.com/manual/reference/method/db.collection.update/#db.collection.update" rel="nofollow">docs</a> about <code>update</code></p>

python mongodb pymongo