我正在使用 Python 和 MongoEngine 尝试在 MongoDB 中查询以下文档。
只有当文档包含符合以下条件的嵌入文档“关键字”时,我才需要查询才能有效地获取文档:
示例结构:
{
"_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 的新手,我正在努力弄清楚如何构建查询并且未能找到类似于我正在尝试做的示例(RED FLAG RIGHT ????)。
我确实找到了一个聚合的例子,但不确定如何在其中构建我的标准,也许像这样的事情越来越接近但不起作用。
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
希望能帮助到你
注意,
sfr
为了简单起见,我只使用了关键字数组中的属性
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句