简体   繁体   中英

How to convert this mongo query to pymongo code?

I have wrote some mongo query. but I can't use this query in pymongo.

I tried to use "$lookup" but my mongo version is 3.4, and it doesn't support pipeline. So I wrote queries. But I have no idea to store query results to mongodb 'var' in python.

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).

From W3Schools you can create queries like so

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)

so in your case it would be along the lines of:

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

You also do not need the var in python. As in python you do not need to declare the variable type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM