MongoDB Python MongoEngine - 通过过滤后的嵌入文档总和过滤器返回文档 属性

MongoDB Python MongoEngine - Returning Document by filter of Embedded Documents Sum of Filtered property

我正在使用 Python 和 MongoEngine 尝试查询 MongoDB 中的以下文档。

我需要一个查询来有效地获取包含符合以下条件的嵌入文档'Keywords'的文档:

示例结构:

{ 
    "_id" : ObjectId("5eae60e4055ef0e717f06a50"), 
    "registered_data" : ISODate("2020-05-03T16:12:51.999+0000"), 
    "UniqueName" : "SomeUniqueNameHere", 
    "keywords" : [
        {
            "keyword" : "carport", 
            "search_volume" : NumberInt(10532), 
            "sfr" : NumberInt(20127), 
            "percent_contribution" : 6.47, 
            "competing_product_count" : NumberInt(997), 
            "avg_review_count" : NumberInt(143), 
            "avg_review_score" : 4.05, 
            "avg_price" : 331.77, 
            "exact_ppc_bid" : 3.44, 
            "broad_ppc_bid" : 2.98, 
            "exact_hsa_bid" : 8.33, 
            "broad_hsa_bid" : 9.29
        }, 
        {
            "keyword" : "party tent", 
            "search_volume" : NumberInt(6944), 
            "sfr" : NumberInt(35970), 
            "percent_contribution" : 4.27, 
            "competing_product_count" : NumberInt(2000), 
            "avg_review_count" : NumberInt(216), 
            "avg_review_score" : 3.72, 
            "avg_price" : 210.16, 
            "exact_ppc_bid" : 1.13, 
            "broad_ppc_bid" : 0.55, 
            "exact_hsa_bid" : 9.66, 
            "broad_hsa_bid" : 8.29
        }
    ]
}

根据我一直在做的研究,我相信聚合类型查询可能会完成我正在尝试的事情。

不幸的是,作为 MongoDB/MongoEngine 的新手,我正在努力弄清楚如何构造查询,但未能找到与我尝试做的类似的示例(红旗正确??? ?).

我确实找到了一个聚合示例,但不确定如何在其中构建我的标准,也许像这样的东西越来越接近但不起作用。

pipeline = [
    { 
        "$lte": {
            "$sum" : {
                "keywords" : {
                    "$lte": {
                        "keyword": 100000
                    }
                }
            }: 9
        }
    }
]
data = product.objects().aggregate(pipeline)

任何指导将不胜感激。

谢谢, 本

你可以试试这个

db.collection.aggregate([
  {
    $project: { // the first project to filter the keywords array
      registered_data: 1,
      UniqueName: 1,
      keywords: {
        $filter: {
          input: "$keywords",
          as: "item",
          cond: {
            $lte: [
              "$$item.sfr",
              100000
            ]
          }
        }
      }
    }
  },
  {
    $project: { // the second project to get the length of the keywords array
      registered_data: 1,
      UniqueName: 1,
      keywords: 1,
      keywordsLength: {
        $size: "$keywords"
      }
    }
  },
  {
    $match: { // then do the match
      keywordsLength: {
        $gte: 9
      }
    }
  }
])

你可以在这里测试Mongo Playground

希望对您有所帮助

Note, I used sfr property only from the keywords array for simplicity