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
user1837631
3491 gold badge3 silver badges4 bronze badges
1 Answer 1
Use dot notation:
$newdata = array('$set' => array('abcd.city' => "Tiruppur"));
answered Jul 5, 2015 at 16:49
TechWisdom
4,3455 gold badges39 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
user1837631
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
TechWisdom
@user1837631, I see. Check out my edited answer and tell me what is going on please.
TechWisdom
@user1837631, You are welcome my friend. I'll be glad if you could mark this as the answer (the V at the left). Thanks.
default