Python Conver";区别于;使用Pymongo从Mongodb中的Sql查询

Python Conver";区别于;使用Pymongo从Mongodb中的Sql查询,python,sql,mongodb,pymongo,Python,Sql,Mongodb,Pymongo,我正在尝试从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 但它似乎不起作用。你有什么建议吗?我做错了什么,但我找不到什么 试试这个管道

我正在尝试从
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

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

试试这个管道:

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
            }
        }
    ]
)

。谢谢您的回答。$replacewith是否会更改我数据库中的任何内容?它似乎不会work@xaroulisgekas
$replaceWith
不会更改数据库中的任何内容。如果您转到我发布的mongoplayground链接,查询确实有效。但是,我错误地使用了
timestamp
intead的
timestamp1
字段名。只需重命名它,它就可以在数据库中工作。
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
            }
        }
    ]
)