MongoDB sorting

前端 未结 4 1575
伪装坚强ぢ
伪装坚强ぢ 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: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 })
    

提交回复
热议问题