35039

How to store sorted array back to MongoDB?

In MongoDB, what's the most efficient approach to sort an array in a document and then store the sorted array back to the document?

For background, I have a process that generates a collection of time stamped data and stores it to the DB, however it's not guaranteed to be stored in time-sequential order. Once the data collection is complete, I'd like to sort the array of data by time and write it back to the DB since all of the future queries on the data will always require sorting by time.

Thanks!

Answer1:

There's no in-place array sorting in MongoDB. Read that array into PHP (or whatever), sort it there and save back.

db.collection.update({_id: document_id}, {$set: {myarray: [3, 2, 1]}});

When you later will read that array, it will stay sorted.

Answer2:

The 2.4 release of MongoDB provides another option here, which is to keep the array field in sorted order as you update it by using the $sort modifier.

db.collection.update({_id: document_id}, {
    $push: {
        myarray: {
            $each: [{timestamp: 456, x: 1}, {timestamp: 123, x: 2}, ...],
            $sort: {timestamp: 1}
        }
    }
});


This will result in the elements of the myarray field of the updated doc to be stored sorted by ascending timestamp.

If you just want to sort the existing elements in place without adding any new ones, use $each: []:

db.collection.update({_id: document_id}, {
    $push: {
        myarray: {
            $each: [],
            $sort: {timestamp: 1}
        }
    }
});

    

Recommend

  • Character strings in Fortran: Portable LEN_TRIM and LNBLNK?
  • scanf in while loop
  • Execution order of expressions in SELECT statement
  • Why is this generic method unsafe?
  • Multiprocessing pool example (parallel) is slower than sequential. Trying to understand pool in pyth
  • How to force Composer to download a local package?
  • Always require certain dependencies in RequireJS
  • C++/CLI Thread synchronization including managed and unmanaged code
  • TSQL Rolling Average of Time Groupings
  • File loader changed image file name but not the file name in HTML file
  • PHP + XML - how to rename and delete XML elements using SimpleXML or DOMDocument?
  • TFS - how do I sum child task hours to parent
  • Detecting # in Scheme list
  • Cypher - matching two different possible paths and return both
  • Examples of how to a STS in .Net 4.5 using WCF
  • Can I use AllJoyn Framework for Wifi Direct in iOS?
  • passing a default argument to a browserify module
  • MySQL performance when updating row with FK
  • HttpListener.IsSupported is false on XP SP3
  • Why must we declare a variable name when adding a method to a struct in Golang?
  • android google indoor map
  • rspec simple example getting error on request variable in integration test
  • How can I extract results of aggregate queries in slick?
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Keep this build forever option - Jenkins
  • Is there a perl module to validate passwords stored in “{crypt}hashedpassword” “{ssha}hashedpassword
  • How can I sort a a table with VBA with given text condition?
  • Converting a WriteableBitmap image ToArray in UWP
  • How to attach a node.js readable stream to a Sendgrid email?
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Is there any way to access browser form field suggestions from JavaScript?
  • Spray.io: When (not) to use non-blocking route handling?
  • Hazelcast - OperationTimeoutException
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • Turn off referential integrity in Derby? is it possible?
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app