uuzhangyu
uuzhangyu

Reputation: 19

MongoDB Update $push Cannot apply the positional operator without a corresponding query field containing an array

model:

{
    "_id" : "a62107e10f388c90a3eb2d7634357c8b",
    "_appid" : [
        {
            "_id" : "1815aaa7f581c838",
            "events" : [
                {
                    "_id" : "_TB_launch",
                    "boday" : [
                        {
                            "VERSIONSCODE" : "17",
                            "NETWORK" : "cmwap",
                            "VERSIONSNAME" : "2.4.0",
                            "IMSI" : "460026319223205",
                            "PACKAGENAME" : "com.androidbox.astjxmjmmshareMM",
                            "CHANNELID" : "xmjmm17",
                            "CHANNELNAME" : "浠..?.M寰.俊?.韩?.?1.x锛.,
                            "eventid" : "_TB_launch",
                            "uuid" : "a62107e10f388c90a3eb2d7634357c8b",
                            "creattime" : "1366300799766",
                            "ts" : ISODate("2013-04-25T06:28:36.403Z")
                        }
                    ],
                    "size" : 1
                }
            ],
            "size" : 1
        }
    ],
    "size" : 1
}
> db.events.update(
    {
        "_id":"039e569770cec5ff3811e7410233ed27",
        "_appid._id":"e880db04064b03bc534575c7f831a83a",
        "_appid.events._id":"_TB_launch"
    },
    {
        "$push":{
            "_appid.$.events.$.boday":{"111":"123123"}
        }
    }
);

Cannot apply the positional operator without a corresponding query field containing an array.

Why?!!

Upvotes: 1

Views: 3030

Answers (2)

Carlos Rodriguez
Carlos Rodriguez

Reputation: 883

Response Here The short answer is, "no", but working with nested arrays gets tricky. Here is an example:

db.foo.save({_id: 1, a1:[{_a1id:1, a2:[{a2id:1, a3:[{a3id:1, a4:"data"}]}]}]})
db.foo.find()
{ "_id" : 1, "a1" : [
 { "_a1id" : 1, "a2" : [
  { "a2id" : 1, "a3" : [
   { "a3id" : 1, "a4" : "data" }
  ] }
 ] }
] }

db.foo.update({_id:1}, {$push:{"a1.0.a2.0.a3":{a3id:2, a4:"other data"}}})
db.foo.find()
{ "_id" : 1, "a1" : [
 { "_a1id" : 1, "a2" : [
  { "a2id" : 1, "a3" : [
   { "a3id" : 1, "a4" : "data" }, 
   { "a3id" : 2, "a4" : "other data" }
  ] }
 ] }
] }

If you are unsure where one of your sub-documents lies within an array, you may use one positional operator, and Mongo will update the first sub-document which matches. For example:

db.foo.update({_id:1, "a1.a2.a2id":1}, {$push:{"a1.0.a2.$.a3":{a3id:2, a4:"other data"}}}) 

Upvotes: 0

Asya Kamsky
Asya Kamsky

Reputation: 42352

You are trying to reference multiple levels of embedding - you can only have one positional $ operator. You won't be able to do something like this until this feature request has been implemented.

Upvotes: 2

Related Questions