Mongodb获取CommandCursor的计数()

2024-07-03 05:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用此聚合执行搜索,并希望获得我的总计数(以处理分页)

results = mongo.db.perfumes.aggregate(
    [
        {"$match": {"$text": {"$search": db_query}}},
        {
            "$lookup": {
                "from": "users",
                "localField": "author",
                "foreignField": "username",
                "as": "creator",
            }
        },
        {"$unwind": "$creator"},
        {
            "$project": {
                "_id": "$_id",
                "perfumeName": "$name",
                "perfumeBrand": "$brand",
                "perfumeDescription": "$description",
                "date_updated": "$date_updated",
                "perfumePicture": "$picture",
                "isPublic": "$public",
                "perfumeType": "$perfume_type",
                "username": "$creator.username",
                "firstName": "$creator.first_name",
                "lastName": "$creator.last_name",
                "profilePicture": "$creator.avatar",
            }
        },
        {"$sort": {"perfumeName": 1}},
    ]
)

如何获取路由中的results计数,以便将其传递给模板

我不能使用results.count(),因为它是命令游标

请帮忙?谢谢


Tags: textnameiddbdatemongomatchusername
2条回答

如果查看CommandCursor的文档,它不支持count()

您可以在jinja模板中使用^{}过滤器

{{ results | length }}

我希望以上内容能有所帮助

使用len方法返回数组中的元素数会更容易,但如果您仍然希望聚合查询同时返回计数和实际文档,请尝试使用$facet$group

查询1:

 {
    $facet: {
      docs: [ { $match: {} } ], // passes all docs into an array field
      count: [ { $count: "count" } ] // counts no.of docs
    }
  },
  /** re-create count field from array of one object to just a number */
  {
    $addFields: { count: { $arrayElemAt: [ "$count.count", 0 ] } }
  }

测试:mongoplayground

查询2:

 /** Group all docs without any condition & push all docs into an array field & count no.of docs flowing through iteration using `$sum` */
{
   $group: { _id: "", docs: { $push: "$$ROOT" }, count: { $sum: 1 } }
}

测试:mongoplayground

注意:

在当前聚合管道的末尾添加其中一个查询,请记住,如果在$match$unwind阶段之后没有文档,那么第一个查询将不会有count字段,而是有docs : [],但第二个查询将只返回[],并对其进行相应的编码

相关问题 更多 >