【问题标题】:How to convert this mongo query to pymongo code?如何将此 mongo 查询转换为 pymongo 代码?
【发布时间】:2019-06-21 16:24:52
【问题描述】:

我写了一些 mongo 查询。但我无法在 pymongo 中使用此查询。

我尝试使用“$lookup”,但我的 mongo 版本是 3.4,它不支持管道。所以我写了查询。但我不知道在 python 中将查询结果存储到 mongodb 'var' 中。

var user_ids = db.register.find({
        "$and": [
            {"_id": {"$gte": ObjectId("5d0a4df00000000000000000")}}
            ,{"_id": {"$lt": ObjectId("5d0b9f700000000000000000")}}
    ]}).map(function(register){
        return register.user_id;
        });

db.login.find({
        "$and": [
            {"_id": {"$gte": ObjectId("5d0b9f700000000000000000")}}
            ,{"_id": {"$lt": ObjectId("5d0cf0f00000000000000000")}}
            ,{"user_id": {"$in": user_ids}}
    ]});

I wanna convert those queries to python code(pymongo).

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    W3Schools 你可以像这样创建查询

    import pymongo
    
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["mydatabase"]
    mycol = mydb["customers"]
    
    for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
      print(x)
    

    所以在你的情况下,它会是:

    from bson.objectid import ObjectId
    
    user_ids = db.register.find({},{
        "$and": [
            {"_id": {"$gte": ObjectId("5d0a4df00000000000000000")}}
            ,{"_id": {"$lt": ObjectId("5d0b9f700000000000000000")}}
    ]}).map(function(register){
        return register.user_id;
        });
    
    db.login.find({}, $and": [
                {"_id": {"$gte": ObjectId("5d0b9f700000000000000000")}}
                ,{"_id": {"$lt": ObjectId("5d0cf0f00000000000000000")}}
                ,{"user_id": {"$in": user_ids}}
        ]}
    

    你也不需要 python 中的var。与在 python 中一样,您不需要声明变量类型。

    【讨论】:

    • 谢谢,杰克。但这两个查询是相关的。 'user_ids' 变量包含第一个查询的结果(它的计数约为百万)。然后它是第二个查询时 $in 子句的参数。
    • 请立即尝试
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2022-01-17
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2018-11-02
    相关资源
    最近更新 更多