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

Asa*_*qri 2 mongodb pymongo

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

{

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

}
Run Code Online (Sandbox Code Playgroud)

我想更新文档的“Needs_Updation”值。

我尝试过以下操作:

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

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

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

我正在使用 PyMongo,有没有办法更新此类文档?

H. *_* U. 5

您的查询在 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
Run Code Online (Sandbox Code Playgroud)