Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB in PHP - How do I insert items into an array in a collection?

This has to be easy, but i can't seem to figure it out... Let say i had a collection users and this is the first item in the collection:

{ 
    "_id" : ObjectId("4d8653c027d02a6437bc89ca"), 
    "name" : "Oscar Godson", 
    "email" : "[email protected]", 
    "password" : "xxxxxx", 
    "tasks" : [
    {
        "task" : "pick up stuff",
        "comment" : "the one stuff over there"
    },
    {
        "task" : "do more stuff",
        "comment" : "lots and lots of stuff"
    }
] }

How with the PHP driver for MongoDB would I then go and add another "task" to the "tasks" array in this item in a collection

like image 789
Oscar Godson Avatar asked Mar 20 '11 19:03

Oscar Godson


People also ask

How do I add elements to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I add an array of strings in MongoDB?

ArrayList<String> stringArray = new ArrayList<String>(); BasicDBObject document = new BasicDBObject(); document. put("master", stringArray); db. getCollection("master"). insert(document);

Can we store array of objects in MongoDB?

One of the benefits of MongoDB's rich schema model is the ability to store arrays as document field values. Storing arrays as field values allows you to model one-to-many or many-to-many relationships in a single document, instead of across separate collections as you might in a relational database.


1 Answers

Use Mongo's $push operation:

$new_task = array(
  "task" => "do even more stuff",
  "comment" => "this is the new task added"
);
$collection->update(
  array("_id" => ObjectId("4d8653c027d02a6437bc89ca")), 
  array('$push' => array("tasks" => $new_task))
);
like image 127
Pablo Avatar answered Nov 02 '22 04:11

Pablo