robinnnnn
robinnnnn

Reputation: 1735

Manipulating the order of elements in an array of references in MongoDB

I'm working on implementing an image album and would like an elegant solution for storing the order of its images. The Album model holds an array of references to Images as follows:

// Example album
{
    _id: 12345
    images: [ObjectId(1), ObjectId(2), ObjectId(3)]
}

// Example image
{
    _id: 1
    title: My Picture
    author: Me
}

I'm trying to figure out how to handle an order update in the database. For example, let's say I'd like to update the array of images from:

[ObjectId(1), ObjectId(2), ObjectId(3)]

to

[ObjectId(3), ObjectId(1), ObjectId(2)]

I'm wondering whether 1) I can directly reorganize an array of references via an update, or 2) if I can, how I can go about actually accessing each element in the array to dictate the new order.

Actually, this solution might be quite useless because the array could be populated asynchronously. An alternative solution would be to ignore what I'm asking for entirely, and store the order of each image individually as follows:

// Image
{
    _id: 1
    title: My Picture
    author: Me
    position: 2    // like this
}

This way when I pull down an array of images asynchronously, all I have to do is sort by each image's position field.

A downside to this strategy is that as the number of images gets sufficiently large, reordering will become quite costly. Moving the final element of a 100-length array to the very beginning would require that I update every single image's position value in the database.

Please let me know if you have any suggestions!

Upvotes: 2

Views: 126

Answers (1)

Alex Blex
Alex Blex

Reputation: 37038

Order of elements in array remains the same as it was persisted.

To change the order, update the array with the order you like. E.g.:

db.album.update({_id:1}, {$set:{images:[ObjectId(3), ObjectId(1), ObjectId(2)]}});

Upvotes: 1

Related Questions