0

How can I insert a new value in MongoDb Column Array?

    // Connect Collection
    $collection = $this->mongo_db->db->selectCollection('test');
// Remove All Document $collection->remove(); // initially Insert abcd Column inside Firstnam Lastname Value $test=array('abcd'=> array("firstname" => "Bob", "lastname" => "Jones" ) );
// Insert Value $content=$collection->insert($test);
// get Last Insert ID $newDocID = $test['_id'];
// Append New value in above abcd Array Field Column $newdata = array('$set'=> array('abcd'=> array('city'=>"Tiruppur")) );
$collection->update(array("_id" => new MongoId($newDocID)), $newdata);

    // Current Result
                {
                    "_id" : ObjectId("55995b0be5ffc4980b000041"),
                    "abcd" : {
                        "city" : "Tiruppur"
                    }
                }
// But Need Expect Result
{ "_id" : ObjectId("55995b0be5ffc4980b000041"), "abcd" : { "firstname" => "Bob", "lastname" => "Jones" , "city" : "Tiruppur" } }
// Please be help to Find Solution

1 Answer 1

0

Use dot notation:

$newdata = array('$set' => array('abcd.city' => "Tiruppur"));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You for u r response TECHWISDOM, But This Ans is Wrong, i am Already try this Code, But Got Error : The field 'abcd' must be an array but is of type Object in document {_id: ObjectId('559aa69ee5ffc4680c000043')} error code: 16837
@user1837631, I see. Check out my edited answer and tell me what is going on please.
@user1837631, You are welcome my friend. I'll be glad if you could mark this as the answer (the V at the left). Thanks.

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.