xiaovid
xiaovid

Reputation: 11

Pymongo Insertion in Document

Here is a concrete example: The name of database is 'twitterDB'. The name of collection is 'userSets'.

The original data in userSets:

user_info={
"name":"britneyspears",
"password":12345,
"image":"/static/image/britney-spears-wallpaper.jpg",
"age":32,
"email":"[email protected]",
"tweets":[
    {"time":"Nov. 18, 2013",
     "content":"I have always been interested in the scientific discoveries underlying health advances in developing countries. The benefits of such breakthroughs are substantial, with the potential to save hundreds of thousands of lives."
    },

    {"time":"Nov. 1, 2013",
     "content":"How cool is that? I asked him to pay off my student loans if he got me. I guess that is a no go now. ;-)"
    },

    {"time":"Dec. 20, 2013",
     "content":"I laughed really hard at that. Those are wonderful gifts, and you are an awesome receiver! Very entertaining experience :)"
    },

    {"time":"Dec. 24, 2013",
     "content":"That is amazing! The picture alone is worth it!!"
    }
]

}

I wanna insert the following new data in "tweets" which is in the same document in userSets: data={"content":"this is xiaovid here!", "time":"Dec. 30, 2013"}

Here is my code for the implementation:

import pymongo
from pymongo import MongoClient

conn=MongoClient()
db=conn.twitterDB
db=db.userSets
x=db.find_one()
x["tweets"].append(data)
db.save(x)

It works but i don't know why the position of the parameter "image" changes after insertion. Besides, I wonder if there is any more normal and effective methods to insert data in document.

Upvotes: 1

Views: 116

Answers (1)

shx2
shx2

Reputation: 64298

You can append a value to an array in a single operation using the $push operator, in an update command. E.g.,

db.update({"name":"britneyspears"}, {"$push": {"tweets": data}})

In the code you posted, the "image" field potentially changes its position because pymongo converts document to a python dict, which is un-ordered. Therefor the order of fields is not guaranteed to be preserved when you read-then-write using pymongo (even if you only read a document, the order of fields in the dict you get is not guaranteed to be the same as in the DB). Ordinarily, you shouldn't worry about the order of the fields at all, because the fields are typically accessed by name.

Using the update+push example above, the order of fields is preserved.

Upvotes: 1

Related Questions