python - 如何将此 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).
解决方案
从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 中一样,您不需要声明变量类型。
推荐阅读
- ruby - 如何使用两个数组在 Ruby 中执行一对一映射?
- sql - 我正在尝试从 sql server 中的列中获取特定值但出现错误
- c# - 如何在 C# WinForm 中实现“office 2016 文件菜单”
- java - 为什么转换为 int 给我 8 而不是 0?
- c# - pdf文件上不同类型的签名
- java - 使用 java 和 selenium 3 的边缘铬无头模式
- java - 对 Oracle Db 使用准备语句,违反唯一约束
- r - R用ifelse改变多列
- ios - 没有名为“FlutterPlugin”的类型或协议
- python - 如何在 python 的输出中显示我的程序代码?