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

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:How to store sorted array back to MongoDB?