如何将排序后的数组存储回MongoDB? [英] How to store sorted array back to MongoDB?

查看:96
本文介绍了如何将排序后的数组存储回MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

对于背景,我有一个生成时间戳数据集合并将其存储到DB的过程,但是不能保证它按时间顺序存储.数据收集完成后,我想按时间对数据数组进行排序,然后将其写回数据库,因为将来对数据的所有查询将始终需要按时间进行排序.

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.

谢谢!

推荐答案

MongoDB中没有就地数组排序.将数组读入PHP(或其他任何语言),在那里排序并保存.

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.

这篇关于如何将排序后的数组存储回MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆