我有次一個領域的蒙戈文件:有沒有辦法在mongo文檔中維護一個有序數組?
field :times, type: Array, default: []`
目前,在更新,我會採取另一種時間,找到自己的位置,並覆蓋上保存整個陣列。有一個更好的方法嗎?有沒有辦法通過Mongo自動執行此操作?
我有次一個領域的蒙戈文件:有沒有辦法在mongo文檔中維護一個有序數組?
field :times, type: Array, default: []`
目前,在更新,我會採取另一種時間,找到自己的位置,並覆蓋上保存整個陣列。有一個更好的方法嗎?有沒有辦法通過Mongo自動執行此操作?
您可以在$push
$push: {
innerElement: {
$each: [
{
"new-entry": ObjectId("xxxxxxx"),
"createdOn": ISODate()
}
],
$slice:-10,
$sort: {'createdOn': 1}
}
使用$sort
可以使用$position
運營商做一個在$push
一個update(...)
時:
>db.students.save({ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] })
>db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 20, 30 ],
$position: 2
}
}
}
)
> db.students.find()
{ "_id" : 1, "scores" : [ 50, 60, 20, 30, 70, 100 ] }
見 - https://docs.mongodb.com/manual/reference/operator/update/position/#up._S_position
什麼樣的元素,你存儲在陣列中,你如何對它們進行排序? – Stefan
我只在數組中放置浮點數。 – unflores