我正在使用Python和MongoEngine尝试在MongoDB中查询以下文档。
只有当文档包含符合以下条件的嵌入式文档"关键字"时,我才需要一个查询来有效地获取文档:
- 筛选关键字,其中属性"SFR"为LTE"100000">
- 对筛选的关键字求和
- 返回匹配条件的关键字之和大于"9"的父文档
示例结构:
{
"_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
}
]
}
根据我所做的研究,我相信Aggregate类型查询可能会达到我所尝试的效果。
不幸的是,作为MongoDB/MongoEngine的新手,我很难弄清楚如何构建查询,并且未能找到一个与我尝试做的类似的示例(RED FLAG RIGHT???(。
我确实找到了一个聚合的例子,但不确定如何在其中构建我的标准,也许这样的东西越来越接近,但不起作用。
pipeline = [
{
"$lte": {
"$sum" : {
"keywords" : {
"$lte": {
"keyword": 100000
}
}
}: 9
}
}
]
data = product.objects().aggregate(pipeline)
如有任何指导,我们将不胜感激。
谢谢,Ben
您可以尝试类似的东西
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
希望它能帮助
注意,为了简化,我只在关键字数组中使用了
sfr
属性