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
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.
ArrayList<String> stringArray = new ArrayList<String>(); BasicDBObject document = new BasicDBObject(); document. put("master", stringArray); db. getCollection("master"). insert(document);
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.
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))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With