下面是一个具体的例子: 数据库的名称是“twitterDB”。 集合的名称为“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”中插入以下新数据,它位于用户集中的同一文档中: data={“content”:“这里是小维!”,“时间”:“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”的位置在插入后会发生变化。 另外,我想知道是否有更正常有效的方法在文档中插入数据。你知道吗
可以使用
update
命令中的$push运算符在单个操作中将值附加到数组中。例如在您发布的代码中,“image”字段可能会更改其位置,因为pymongo将文档转换为python
dict
,这是无序的。因此,当您使用pymongo读然后写时,不能保证字段的顺序被保留(即使您只读取文档,也不能保证您得到的dict
中的字段顺序与DB中的相同)。通常,您根本不应该担心字段的顺序,因为字段通常是通过名称访问的。你知道吗使用上面的
update+push
示例,字段的顺序被保留。你知道吗相关问题 更多 >
编程相关推荐