MongoDB sorting

前端 未结 4 1470
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 13:23

I want implement a \"bump\" feature for topics. Once a topic is bumped, it will have a new \"bump_date\" field. I want to sort it so that when there is a \"bump_date\" fie

相关标签:
4条回答
  • 2020-12-13 13:33

    As Brian Hicks suggested, creating an additional updated_at field is the way to go. This way, when a document is created you can have created_at and updated_at initially be the same.

    {
         "created_at": xxx,
         "updated_at": xxx
    }
    

    If you then "bump" the updated_at field by setting it to the current time when there is a a bump event you can sort on the updated_at field to achieve the ordering you desire.

    0 讨论(0)
  • 2020-12-13 13:35

    Currently it is not possible in mongodb to do a sort based on user defined criteria over multiple columns.eg. here the function would have been to return bump_date if it is set,else return created

    Either you will have to use a server-side or client-side code as mentioned here :

    Mongo complex sorting?

    or if you want to stay with basic quering and sorting, you shall :

    • create a key bump_date equivalent to created whenever a new record is created. This will not be a data overhead, as you can expect every topic of yours to be bumped once in a while in future,hence bump_date field will eventually be added. So add it from the start itself.

    • Whenever the article is bumped,update the field bump_date .

    Your example documents will look like this with this change :

    {
        "text" : "test 1",
        "created" : "Sun Nov 20 2011 02:03:28 GMT-0800 (PST)",
        "bump_date" : "Sun Nov 20 2011 02:03:28 GMT-0800 (PST)"
    },
    {
        "text" : "test 2",
        "created" : "Sun Nov 18 2011 02:03:28 GMT-0800 (PST)",
        "bump_date" : "Sun Nov 18 2011 02:03:28 GMT-0800 (PST)" 
    },
    {
        "text" : "test 3",
        "created" : "Sun Nov 17 2011 02:03:28 GMT-0800 (PST)",
        "bump_date: : "Sun Nov 19 2011 02:03:28 GMT-0800 (PST)"
    }
    

    You shall ensureIndex on bump_date field. Now you can query the required data easily.

    db.topics.find().sort({ bump_date: 1 })
    
    0 讨论(0)
  • 2020-12-13 13:39

    Sorting in MongoDB is done like so:

    db.collection.find({ ... spec ... }).sort({ key: 1 })

    where 1 is ascending and -1 is descending.

    In your specific example: db.topics.find().sort({ bump_date: 1 }), although it might be better to call it something like "updated_at".

    You'll also definitely want to put an index on your "bump_date" field.

    • sorting: http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order
    • indexes: http://www.mongodb.org/display/DOCS/Indexes
    0 讨论(0)
  • 2020-12-13 13:39

    Also:

    db.collection.find( { $query: {}, $orderby: { column : -1 } } )
    

    where 1 is ascending and -1 is descending.

    0 讨论(0)
提交回复
热议问题