首页 > 解决方案 > 如何将此 mongo 查询转换为 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).

标签: pythonmongodbpymongo

解决方案


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

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


推荐阅读