php - Mongodb: read documents/arrays and delete them immediately -
php - Mongodb: read documents/arrays and delete them immediately -
technical background: i'm using tokumx (support document level locking) , php.
the document construction this
{ "accounts": [ { "username": "1", }, { "username": "2", } ], "site": "test.com" }
situation:
most of time, need first x accounts "accounts" array.
the minutes these first x accounts retrieved, should deleted "accounts" array in document.
compromise can make:
extract out "accounts".
{ "username" : "1", "site": "test.com" }, { "username" : "2", "site": "test.com" }
or switch mysql (last option).
this comment, it's long comment more explaination , illustration given. not familiar tokumx ( in, have never used ), mongodb has way this, , it's .findandmodify()
method.
basically "updating" document or "removing" in case, have alternative see either "pre-modified" or "post-modified" form in returned result.
so work array phone call this:
$doc = $collection->findandmodify( array(), # representing "query" array( '$pull' => array( # basicallly update 'accounts' => array( 'username' => 1 ) ) ), null, # optional projected fields array( # "options" "new" => false, # default ) );
and plain document:
$doc = $collection->findandmodify( array( 'username' => 1 ), array(), # update, doesn't matter null, array( "remove" => true ) );
noting comment, remove first n
elements of array using $push
operator funnily enough. there $slice
modifier this:
$doc = $collection->findandmodify( array(), # representing "query" array( '$push' => array( # basicallly update 'accounts' => array( '$each' => array(), # blank '$slice' => lengthofarrayminusnelements ) ) ), null, # optional projected fields array( # "options" "new" => false, # default ) );
not "super" atomic since need know "how long" array is, can done. seems odd know, adding "nothing" array limiting it's length , removing elements via $slice
. 2 forms, 1 projection, other update modifier shown.
php mongodb mongodb-query
Comments
Post a Comment