Django 函数 return MongoDB 聚合管道的结果

Django function to return the result of MongoDB aggregate pipeline

如果有人能帮助我,我将不胜感激。我需要 Django (Python) 函数将一些参数注入管道脚本,将其传递给 MongoDB Atlas 并在游标中接收结果。

from bson import ObjectId
import pymongo

conn = "connection string"
client = pymongo.MongoClient(conn) 

pipeline = [
    <<pipeline script>>
    ]

out = client.db.mycollection.aggregate(pipeline)

如果您使用 Djongo 将 Django ORM 连接到 MongoDB,您可以使用提供的 DjongoManager 作为您模型的管理器,并使用 PyMongo 函数使用 mongo_ 字首。这是一个简单的例子:

models.py

from djongo import models

class Message(models.Model):
    text = models.CharField(max_length=150)

    objects = models.DjongoManager()

然后在 shell 中你可以这样做:

>>> from core.models import *

>>> cursor = Message.objects.mongo_aggregate('pipeline')