0

I'm trying to add php array to MongoDB document

{
    "_id" : ObjectId("51b043e1d07a4e9e06000004"),
    "comments" : {
        "count" : 0,
        "array" : []
    }
}

array:

$array = array(
       "user_id" => $comment["user_id"],
       "text" => $comment["text"]
);

Using this:

$this->database->Collection->update(array("_id" => new MongoId($comment["object_id"])), array('$push' => $array);

However, it doesn't seem to work and I can't find why. I don't know MongoDb well yet... Thanks

1 Answer 1

1

The value of the $push needs to be another PHP array with a key that names the array field to update and a value that's the element to add. So in this case it would be:

$this->database->Collection->update(
    array("_id" => new MongoId($comment["object_id"])), 
    array('$push' => array("comments.array" => $array)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.