【问题标题】:Conver "distinct on" query from Sql in Mongodb with Pymongo使用 Pymongo 从 Mongodb 中的 Sql 转换“distinct on”查询
【发布时间】:2021-04-22 15:27:59
【问题描述】:

我正在尝试从sql 转换此查询:

select distinct on (id13) id13, timestamp1 
from oneindextwocolumnsfalse3years 
where timestamp1>='2010-01-01 00:00:00' and timestamp1<='2015-01-01 00:55:00' 
order by id13,timestamp1 desc

像这样给mongodb

mydb1.mongodbindextimestamp1.aggregate([

    {
        "$match": {
            "timestamp1": {"$gte": datetime.strptime("2010-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"),
                          "$lte" :datetime.strptime("2015-01-01 00:55:00", "%Y-%m-%d %H:%M:%S")}
        }
    },

{
        "$group": {
            "_id":{
                "id_13":"$id13"
        },

      }
},
    {
        "$project": {
            "_id": 0,
            "id13":1,
            "timestamp1":1
        }
    },
    {"$sort": {"id13": 1,"timestamp1":-1}}

])

但它似乎不起作用。你有什么建议吗?我做错了什么,但我找不到什么!

【问题讨论】:

    标签: python sql mongodb pymongo


    【解决方案1】:

    试试这个管道:

    db.collection.aggregate(
        [
            {
                $match: {
                    timestamp: {
                        $gte: ISODate("2020-01-01"),
                        $lte: ISODate("2022-01-01")
                    }
                }
            },
            {
                $group: {
                    _id: "$id13", //define the grouping key
                    doc: { $first: "$$ROOT" } //pick the first doc from each group
                }
            },
            {
                $replaceWith: "$doc" //promote the doc to root
            },
            {
                $project: {
                    _id: 0,
                    id13: "$id13",
                    timestamp: "$timestamp"
                }
            },
            {
                $sort: {
                    id13: 1,
                    timestamp: -1
                }
            }
        ]
    )
    

    https://mongoplayground.net/p/Cwzic2cMfgd

    【讨论】:

    • 。感谢您的回答。$replacewith 会改变我数据库中的任何内容吗?
    • @xaroulisgekas $replaceWith 不会更改数据库中的任何内容。如果您转到我发布的 mongoplayground 链接,该查询确实有效。但是,我错误地使用了字段名称 timestamp 而不是您的 timestamp1。只需重命名它,它应该可以在您的数据库上运行。
    猜你喜欢
    • 2018-11-02
    • 2018-03-11
    • 1970-01-01
    • 2020-03-13
    • 2020-12-29
    • 2017-09-08
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多