【问题标题】:Get distinct values sorted by date_posted in decending order with PyMongo使用 PyMongo 获取按发布日期降序排序的不同值
【发布时间】:2018-09-02 08:40:27
【问题描述】:

下面是我使用的查询

jd = mongo.db.rest_manage_job_format

Type_of_request = jd.find().distinct("Type_of_request").sort('date_posted',-1)

但它给了我类型错误:

TypeError: must use keyword argument for key function

我不知道如何解决。请帮我解决这个问题。

提前致谢!

【问题讨论】:

  • 你可以在这里尝试聚合Type_of_request = (await jd.aggregate([ { "$group": { "_id": "$Type_of_request", "date_posted": { "$first": "$date_posted" } }}, { "$sort": { "date_posted": 1 }} ])).map(({ _id }) => _id)

标签: python mongodb mongodb-query pymongo


【解决方案1】:

.distinct 方法返回一个列表,sort 方法在这里是 list.sort 方法,它只接受关键字参数。

如果你想通过“date_posted”对你的元素进行排序,你需要在调用list.sort时使用.aggregate方法或者传递一个函数给key

【讨论】:

    【解决方案2】:

    distinct() 返回一个列表,你必须对列表进行排序

    jd = mongo.db.rest_manage_job_format
    
    Type_of_request = jd.find().distinct("Type_of_request").sort(reverse=True)
    

    【讨论】:

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