How to store an ordered set of documents in MongoDB without using a capped collection

前端 未结 4 1629
囚心锁ツ
囚心锁ツ 2020-12-28 23:11

What\'s a good way to store a set of documents in MongoDB where order is important? I need to easily insert documents at an arbitrary position and possibly reorder them lat

4条回答
  •  灰色年华
    2020-12-28 23:34

    For abitrary sorting of any collection, you'll need a field to sort it on. I call mine "sequence".

    schema:
    {
     _id: ObjectID,
     sequence: Number,
     ...
    }
    
    db.items.ensureIndex({sequence:1});
    
    db.items.find().sort({sequence:1})
    

提交回复
热议问题