在子文档中推送项目

push item in sub document

我有简单的collection。我想推送有问题的项目,但它给出了 exception.How 我可以解决它吗?

/* 1 */ 我的collection 数据

{
    "_id" : ObjectId("557e8c93a6df1a22041e0879"),
    "QuestionCount" : 2.0000000000000000,
    "Questions" : [ 
        {
            "_id" : ObjectId("557e8c9ba6df1a22041e087a"),
            "DataSource" : [],
            "DataSourceItemCount" : NumberLong(0)
        }, 
        {
            "_id" : ObjectId("557e8c9fa6df1a22041e087b"),
            "DataSource" : [],
            "DataSourceItemCount" : NumberLong(0)
        }
    ],
    "Name" : "er"
}

( id =557e8c93a6df1a22041e0879 and question id = 557e8c9fa6df1a22041e087b)

db.getCollection('forms').update({
    "_id": ObjectId("557e8c93a6df1a22041e0879"),
    "Questions._id": ObjectId("557e8c9fa6df1a22041e087b")
}, {
    "$push": {
    "Questions.DataSource": {
        "_id": ObjectId("557e8e5ea6df1a27b403ff6b"),
        "CreationDate": ISODate("2015-06-15T08:35:42.923Z"),
        "IsActive": true,
        "Text": "op",
        "Value": "op"
    }
    }
})

cannot use the part (Questions of Questions.DataSource) to traverse the element ({Questions: [ { _id: ObjectId('557e8c9ba6df1a22041e087a'), CreationDate: new Date(1434356891784), IsActive: true, Name: "uıo", IsRequired: false, QuestionType: 1, AnswerInputType: 1, AnswerValidationPattern: null, AnswerValidationMessage: null, QuestionOrder: 1, DataSource: [], DataSourceItemCount: 0 }, { _id: ObjectId('557e8c9fa6df1a22041e087b'), CreationDate: new Date(1434356895695), IsActive: true, Name: "ıu", IsRequired: false, QuestionType: 2, AnswerInputType: 1, AnswerValidationPattern: null, AnswerValidationMessage: null, QuestionOrder: 2, DataSource: [], DataSourceItemCount: 0 } ]})

您需要在声明的更新部分中使用 positional $ operator

db.getCollection('forms').update(
    { 
        "_id" : ObjectId("557e8c93a6df1a22041e0879"),
        "Questions._id" : ObjectId("557e8c9fa6df1a22041e087b")
    },
    { 
        "$push" : { 
            "Questions.$.DataSource" : { 
                "_id" : ObjectId("557e8e5ea6df1a27b403ff6b"),
                "CreationDate" : ISODate("2015-06-15T08:35:42.923Z"), 
                "IsActive" : true, 
                "Text" : "op", 
                "Value" : "op" 
            }
        }
    }
)

它标识您要更新的已找到项目的索引。

虽然这对于嵌套数组结构的 $push 操作没问题,但您很快就会发现 "nested arrays" 不适合更新。这里的主要问题是 "positional operator" 只能匹配 "first" 或 "outer" 数组的索引。所以不可能匹配内部数组元素的位置并更新它。

我强烈建议将您的结构更改为 "flatten" 作为更适合这些操作的单个数组。