How can I atomically reorder array items in MongoDB?

I have a playlists collection. Each document in the collection contains an entries field, that is an array.

How can I change the order of entries in a playlist, atomically? (e.g. If another user tries at the same time to $push a new entry, I want to make sure that the new entry is $pushed only after the reordering has happened)

If I do a find(), then reorder in PHP, then update(), I might lose the new $pushed entry if the operation is not atomic.

This is a sample playlist object:

{ "_id" : "playlist1", "title" : "Playlist One", "entries" : [ { "class" : "song", "identifier" : "song1" }, { "class" : "song", "identifier" : "song2" }, { "class" : "song", "identifier" : "song3" } ] }


I think I found a possible solution, using execute():

Running JavaScript in the database takes a write lock, meaning it blocks other operations.


I just need to execute the code (find() + reorder() + update()) on the MongoDB Server.

Still, if you have another idea that doesn't involve "code within a string" (e.g. $func = "function() { do_something(); return \"something else\" }"), please share it.


-------------Problems Reply------------

Using eval() to block operations is a side effect of the current implementation, not a feature to rely on.

The MongoDB wiki has a page with information on Atomic Operations.

A relevant strategy for your use case would be "update if current":

  1. Fetch the object.
  2. Modify the object locally.
  3. Send an update request that says "update the object to this new value if it still matches its old value".
Category:php Views:0 Time:2011-10-17
Tags: php mongodb

Related post

  • Find matching array items in MongoDB document 2012-03-15

    I am developing a web app using Codeigniter and MongoDB. In the database I got a document that look like this: { "_id": { "$id": "4f609932615a935c18r000000" }, "basic": { "name": "The project" }, "members": [ { "user_name": "john", "role": "user", "c

  • How to $set sub-sub-array items in MongoDB 2010-08-13

    I'm developing a webapp which has a portal-ish component to it (think like multiple panels that can be drug around from column to column and added or removed). I'm using MongoDB to store this info with a format like so... { _id: ObjectId(...), title:

  • Remove array item and updating array index 2012-03-29

    How would I go about removing an array item from an array in a way that keeps the array index in an incremental list? Basically I want to do this: Modify the following array so that it results in the next one #before arrayName[0] = "asdf random text"

  • simple question about difference between array.item(n) and array[n]? 2009-08-08

    I have a question. I was recently writing some javascript code in dreamweaver and in it's code complete everytime i would deal with array of elements it will give me array.item(n) rather then array[n] What is the difference between those two ? Some e

  • merging array items in ruby 2009-11-04

    Given an array of arrays [["B", "C", "E", "F"], ["A", "B", "C", "D"], ["G"]] What is the simplest way to merge the array items that contain members that are shared by any two or more arrays items. For example the above should be [["A", "B", "C", "D",

  • How do I delete Perl hash or array items based on their age? 2009-11-18

    How do I delete array items I'm not interested in? If I would leave them—my memory would get overflowed with unnecessary items. I need to implement in Perl one task. One file is being continuously filled with messages containing: "IP - URL" I need to

  • Javascript: How to remove an array item(JSON object) based on the item property value? 2009-12-10

    like this: var arr = [ { name: "robin", age: 19 }, { name: "tom", age: 29 }, { name: "test", age: 39 } ]; I want to remove array item like this(an array prototype method): arr.remove("name", "test"); // remove by name arr.remove("age", "29"); // remo

  • Removing array item by value 2009-12-10

    I need to remove array item with given value: if (in_array($id, $items)) { $items = array_flip($items); unset($items[ $id ]); $items = array_flip($items); } Could it be done in shorter (more efficient) way? --------------Solutions------------- It can

  • Does JavaScript populate empty array items? 2010-01-11

    I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two t

  • Unset blank array items on the fly 2010-02-23

    I have an array which is being built using: $features_data[$i] = preg_split("/\n/", $row); The output is as follows: Array ( [0] => Array ( [0] => [1] => [2] => <img src="

  • Android: Populating a listview with array items 2010-03-06

    I'm new to Android and I think I'm trying to do something really basic: I have a 5 strings in my Array (say 'One', 'Two', ...). I want to add these 5 strings to my list view in my listactivity. My List: <ListView android:id="@+id/android:list" and

  • PHP Is Array Item In Variable 2010-04-19

    I have an array and a variable, I want to check if any of the array items occur in the variable. I presume I somehow use strstr()? Example: $bad = array('', '', ''); $ref = $_SERVER['HTTP_REFERER']; if(ANY OF $bad IS

  • Configuring Cruise Control Net with sourcesafe - Unable to load array item 'executable' 2010-05-07

    I'm trying to create a continuous integration environment. To do so, I've used a guide that can be found at In this step by step, the goal is to create a CI with CCNet, NAnt, NUni, NDoc, FxCop and source saf

  • PHP: Reorder arrays after unset() 2010-09-20

    There are 2 functions involved. Search array items for a given string unset() array item if string not found $array = array("first", "second", "third", "fourth"); foreach($array as $i=> $string) { if(stristr($string, "e")) { unset($array[$i]); } }

  • How do I get the Array Item Type from Array Type in .net 2010-11-09

    Say I have an System.String[] type object. I can query the type object to determine if it is an array Type t1 = typeof(System.String[]); bool isAnArray = t1.IsArray; // should be true However how do I get a type object of the array item from t1 Type

  • Merge array items into string 2011-01-07

    How do I merge all the array items into a single string? --------------Solutions------------- Use implode function php manual implode Eg: $fruits = array('apples', 'pears','bananas'); echo implode(',',$fruits); Try this from php manual (

  • Atomically remove an item from set if a counter in another key is below zero? 2011-02-25

    Redis 2.0.3 In my Redis DB I have a set of items. Each item has a counter, associated with it: MULTI SADD "items-set" "foo" INCRBY "items:foo" 10000 EXEC New items are added to the set at random intervals. When user does a certain action, counter is

  • javascript find parent of array item 2011-03-01

    I have an array item like this: var array = USA.NY[2]; // gives "Albany" {"USA" : { "NY" : ["New York City", "Long Island", "Albany"] }} I want to find the state from just having the array. How do I do this? Thanks. function findParent(array) { // do

  • Javascript array items == "undefined" in Google Maps function 2011-04-18

    Hello I'm looping over a JSON object and creating a new map marker for each item. After the marker is created, I push it to an array (var markers) for future manipulation. Problem is, when I try to access the array items (eg: console.log(markers[3]))

Copyright (C), All Rights Reserved.

processed in 0.209 (s). 11 q(s)