【问题标题】:Pymongo Insertion in DocumentPymongo 在文档中插入
【发布时间】:2014-01-17 13:01:38
【问题描述】:

这是一个具体的例子: 数据库的名称是“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!!"
    }
]

}

我想在 userSets 的同一文档中的“tweets”中插入以下新数据: data={"content":"这里是 xiaovid!", "time":"Dec. 30, 2013"}

这是我的实现代码:

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”的位置在插入后会发生变化。 另外,不知道有没有更正常有效的在文档中插入数据的方法。

【问题讨论】:

    标签: python insert document pymongo


    【解决方案1】:

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

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

    在您发布的代码中,“图像”字段可能会更改其位置,因为 pymongo 将文档转换为无序的 python dict。因此,当您使用 pymongo 读写时,不能保证保留字段的顺序(即使您只阅读文档,也不能保证您获得的 dict 中的字段顺序与D B)。通常,您根本不必担心字段的顺序,因为字段通常是按名称访问的。

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

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多