質問

I'm trying to save() a record inside an object. Problem is I just get MongoCursor()-errors or unexpected 'array' (T_ARRAY). For an instance:

This is my MongoDB-collection:

[
  {
    "id": "dfK15ale12",
    "keys": {
      "gcm_key": "abc",
      "app_secret": "123"
    }
  }

]

I want to update the gcm_key inside keys, this is my PHP code:

$db->apps->save(
    array("_id" => $update['_id'])
    array("$push" => 'keys.gcm_android' => $gcm_android);
);

This gives me the following error:

Parse error: syntax error, unexpected 'array' (T_ARRAY) in C:\xampp\htdocs\api\update.php on line 3

I have googled and looked here on Stack to find answers, and I've found nothing. Maybe I've missed something. I don't know, what is the correct mongoDB cursor and which is the easiest way to save() the gcm_key?

役に立ちましたか?

解決

The operation you seem to want is update

$db->apps->update(
    array('_id' => $update['_id']),
    array('$push' => array('keys.gcm_android' => $gcm_android))
);

But is un-clear what you want your end result to be. This would produce the following:

{
    "_id" : ObjectId("532aa3d15fcd8ecb9ae23567"),
    "id" : "dfK15ale12",
    "keys" : {
            "gcm_key" : "abc",
            "app_secret" : "123",
            "gcm_android" : [
                    123
            ]
    }
}

Assuming that you had value 123 in your $gcm_android variable. If you have an array then look at $pushAll.

If you are just looking to add another property to keys then use $set:

$db->apps->update(
    array('_id' => $update['_id']),
    array('set' => array('keys.gcm_android' => $gcm_android))
);

Where this is your result:

{
    "_id" : ObjectId("532aa3d15fcd8ecb9ae23567"),
    "id" : "dfK15ale12",
    "keys" : {
            "gcm_key" : "abc",
            "app_secret" : "123",
            "gcm_android" : 123
    }
}

他のヒント

$db->apps->update(
    array('_id' => new MongoId('YOURIDGOESHERE')),
    array('$set' => array('keys.gcm_android' => $gcm_android))
);

Your syntax is all wrong:

$db->apps->save(
    array("_id" => $update['_id'])
    array("$push" => 'keys.gcm_android' => $gcm_android);
);

Should be:

$db->apps->update(
    array("_id" => $update['_id']),
    array('$push' => array('keys.gcm_android' => $gcm_android))
);

That is what the error is telling you right here:

unexpected 'array' (T_ARRAY)

It is actually speaking first of the comma and then of the array

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top