如何将此mongo查询转换为pymongo代码?

时间:2019-06-21 07:48:15

标签: python mongodb pymongo

我写了一些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).

1 个答案:

答案 0 :(得分:0)

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中一样,您无需声明变量类型。