使用Pymongo在MongoDB中更新嵌套文档

时间:2015-06-11 13:35:23

标签: mongodb pymongo

以下是我要更新的文档的架构:

{

 "field1" : "value1",
 "field2" : "value2",
 "field3" : {
    "list" : [
        {
            "content" : "valueA",
            "start" : "valueA",
            "group" : "valueA"
        },
        {
            "content" : "valueB",
            "start" : "Needs_Updation",
            "group" : "valueB"
        },
    ]

}

我想更新" Needs_Updation"文件的价值。

我试过以下:

db.collection.update({
    "field1":"value1" , 
    "field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
    {"$set":{"field3.list.$.start" : "Updated_Value"}}
)

还有一个更简单的查询,如:

db.collection.update({
    "field1":"value1" ,
    "field3.list.content":"valueB",
    {"$set":{"field3.list.$.start" : "Updated_Value"}}
)

我使用PyMongo,有没有办法更新这种文件?

1 个答案:

答案 0 :(得分:4)

您的查询在shell中正常运行。您可以尝试以下代码:

import pymongo
#from pymongo import Connection
try:
    conn=pymongo.MongoClient()
    print "Connected successfully!!!"
    db = conn.test     #database name = test
    collection= db.StackOverflow   #collection name= StackOverflow

    record= {
    "field1" : "value1",
    "field2" : "value2",
    "field3" : {
    "list" : [
    {
       "content" : "valueA",
       "start" : "valueA",
       "group" : "valueA"
    },
    {
       "content" : "valueB",
       "start" : "Needs_Updation",
       "group" : "valueB"
    }]
    }
    }
    collection.insert(record)
    for data in collection.find():
        print "Inserted Data=", data

    collection.update({
    "field1":"value1" ,     
    "field3.list" :{"$elemMatch" : {"content" : "valueB","group": "valueB" }}},
     {"$set":{"field3.list.$.start" : "Updated_Value"}}
   )

    for data in collection.find():
        print "Updated Data=", data

except pymongo.errors.ConnectionFailure, e: 
    print "Could not connect to MongoDB: %s" % e 
conn