Pymongo插入文档

时间:2013-12-30 16:01:27

标签: python insert document pymongo

这是一个具体的例子: 数据库的名称是'twitterDB'。 集合的名称是'userSets'。

userSets中的原始数据:

user_info={
"name":"britneyspears",
"password":12345,
"image":"/static/image/britney-spears-wallpaper.jpg",
"age":32,
"email":"britneyspears@example.com",
"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!!"
    }
]

}

我想在“tweets”中插入以下新数据,这些数据位于userSets中的同一文档中: data = {“content”:“这是xiaovid here!”,“time”:“2013年12月30日”}

以下是我的实施代码:

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)

它有效,但我不知道为什么插入后参数“image”的位置会发生变化。 此外,我想知道是否有更正常有效的方法在文档中插入数据。

1 个答案:

答案 0 :(得分:1)

您可以在update命令中使用$push运算符在单个操作中向数组附加值。如,

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

在您发布的代码中,"图像"字段可能会改变其位置,因为pymongo会将文档转换为未命令的python dict。因此,当您使用pymongo进行read-then-write时,不保证保留字段的顺序(即使您只读取文档,您获得的dict中字段的顺序也不能保证与在DB)。通常,您根本不必担心字段的顺序,因为字段通常是通过名称访问的。

使用上面的update+push示例,保留字段的顺序。