【问题标题】:Is there a way to maintain an ordered array within a mongo document?有没有办法在 mongo 文档中维护有序数组?
【发布时间】:2016-11-30 09:10:04
【问题描述】:

我有一个包含时间字段的 mongo 文档:

field :times, type: Array, default: []`

目前,在更新时,我会花点时间,找到它的位置并在保存时覆盖整个数组。有一个更好的方法吗?有没有办法通过 Mongo 以某种方式自动执行此操作?

【问题讨论】:

  • 你在数组中存储什么样的元素以及如何对它们进行排序?
  • 我只是将浮点数放入数组中。

标签: arrays ruby mongodb


【解决方案1】:

你可以在$push中使用$sort

$push: {
    innerElement: {
        $each: [
            {
                "new-entry": ObjectId("xxxxxxx"),
                "createdOn": ISODate()
            }
        ],

        $slice:-10,

        $sort: {'createdOn': 1}
    }

【讨论】:

    【解决方案2】:

    update(...) 中执行$push 时,您可以使用$position 运算符:

    >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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多