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

Barmar
789k57 gold badges555 silver badges669 bronze badges
asked Nov 15, 2013 at 23:31

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)));
answered Nov 16, 2013 at 0:45
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.