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

TechWisdom
4,3455 gold badges39 silver badges43 bronze badges
asked Jul 5, 2015 at 16:38

1 Answer 1

0

Use dot notation:

$newdata = array('$set' => array('abcd.city' => "Tiruppur"));
answered Jul 5, 2015 at 16:49
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

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.