如何更新嵌套的子文档数组中的子文档

时间:2015-03-30 15:12:48

标签: mongodb pymongo

使用mongodb和pymongo,我有以下文件:

{
    "_id" : ObjectId("5515d697453d9a1975123e0b"),
    "Study_Attributes" : [ 
        {
            "value" : "183",
            "tag" : "height",
            "unit" : "cm"
        }, 
        {
            "value" : "92",
            "tag" : "weight",
            "unit" : "kg"
        }
    ],
    "Center_Project_Name" : "prj001",
    "Study_Abstract" : "THIS IS THE ABSTRACT",
    "Study_Description" : "---",
    "Study_Title" : "Study of Wheat",
    "Center_Name" : "cc001",
    "samples" : [ 
        {
            "Scientific_Name" : "aribido",
            "Anonymized_Name" : "XXX001",
            "Description" : "cress",
            "Characteristics" : [ 
                {
                    "value" : "",
                    "id" : ObjectId("5515d6f5453d9a1975123e0c"),
                    "tag" : "",
                    "unit" : ""
                }
            ],
            "Sample_Name" : "XXX001",
            "Common_Name" : "mustard cress",
            "Term_Accession_Number" : "19879",
            "Individual_Name" : "xx1",
            "Taxon_ID" : "19879",
            "_id" : ObjectId("5515d6f5453d9a1975123e0d"),
            "Term_Source_REF" : "TODO:ONTOTLOGY_ID",
            "Protocol_REF" : "TODO:PROTOCOL_STRING",
            "Source_Name" : "cthulu"
        }
    ]
}

我想更新样本子文档(这是一个数组元素,因为可能有多个样本)。我有以下代码,但它不起作用......

EnaCollections.update(
            {"_id": o.ObjectId(study_id), "samples._id": o.ObjectId(sample_id)},
            {'$set:': {
                "samples.$.Source_Name": sample['Source_Name'],
                "samples.$.Characteristics": spec_attr,
                "samples.$.Term_Source_REF": "TODO:ONTOLOGY",
                "samples.$.Protocol_REF": "TODO:PROTOCOL_STRING",
                "samples.$.Sample_Name": sample['Anonymized_Name'],
                "samples.$.Individual_Name": sample['Individual_Name'],
                "samples.$.Description": sample['Description'],
                "samples.$.Taxon_ID": sample['Taxon_ID'],
                "samples.$.Scientific_Name": sample['Scientific_Name'],
                "samples.$.Common_Name": sample['Common_Name'],
                "samples.$.Anonymized_Name": sample["Anonymized_Name"],
            }}
        )

有人可以告诉我这有什么问题吗?

1 个答案:

答案 0 :(得分:1)

查看更新语句,其中指定了$set修饰符,其中包含多余的:

  

...{'$set:': {...

只需删除它,一切都会起作用:)