如何在pymongo(MongoDb)中查找和聚合?

hkmswyz6  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(151)

项目:

[{
    "id": 0,
    "studytypes": [{
        "id": 4000,
        "name": "For all",
        "filter": true
      },
      {
        "id": 4001,
        "name": "For girls",
        "filter": false
      },
      {
        "id": 4002,
        "name": "For boys",
        "filter": false
      }
    ]
  },
  {
    "id": 1,
    "studytypes": [{
        "id": 4000,
        "name": "For all",
        "filter": false
      },
      {
        "id": 4001,
        "name": "For girls",
        "filter": true
      },
      {
        "id": 4002,
        "name": "For boys",
        "filter": false
      }
    ]
  }
]

字符串
1.需要查找idfilter页面
1.需要按idfilter进行聚合,并仅用Truefilter计算所有不同的idname

db["schools"].find({"$and": [{"studytypes.filter":True}, {"studytypes.id": 4000}]}


但它的作品,虽然所有“真”filter s没有"id"的差异
是窃听器还是什么?

snvhrwxg

snvhrwxg1#

1.而不是using“$and”运算符,您需要use“$elemMatch”
第一个月
1.对于以相同方式聚合,需要在管道中use“$match”运算符after“$Unwind”not before and then sort and count it that way
pipeline = [{"$unwind": "$studytypes"},{"$match": {"studytypes.filter": True}},{"$group": {"_id": {"name": "$studytypes.name", "filter": "$studytypes.filter", "id": "$studytypes.id"},"count": {"$sum": 1}}},{"$sort": SON([("count", -1), ("_id", -1)])}]
db["schools"].aggregate(pipeline)

相关问题