You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB聚合查询的$and改为隐式AND解决Python执行报错

Fixing PyMongo's unknown operator: $and Error for Date-Based Aggregation

Hey there! Let's get this sorted out. The error you're hitting has a couple of straightforward fixes, and we can even improve the query's performance while we're at it.

Why Your Original Query Fails

First off, the immediate issue is that your original query uses expr instead of $expr—that missing dollar sign is what's tripping up PyMongo's parser and causing the "unknown operator: $and" error. Even once you fix that, using an explicit $and inside $expr isn't strictly necessary, since MongoDB lets us use implicit logical AND in a cleaner way.

Solution 1: Date Range Query (Preferred, Index-Friendly)

The best way to match all records from a specific month is to use a date range instead of extracting year and month with aggregation operators. This approach is faster because it can use indexes on your timestamp field, and it naturally uses implicit AND without needing $and or $expr at all.

Here's how to implement it in Python:

from datetime import datetime

# Define the start and end of January 2016
start_of_month = datetime(2016, 1, 1)
start_of_next_month = datetime(2016, 2, 1)

match_stage = {
    "$match": {
        "timestamp": {
            "$gte": start_of_month,
            "$lt": start_of_next_month
        }
    }
}

This query will match every document where timestamp falls on or after January 1, 2016, and before February 1, 2016—exactly the same as filtering for year 2016 and month 1. And since we're using $gte and $lt in the same query object, MongoDB treats them as an implicit AND automatically.

Solution 2: Corrected Aggregation Operator Syntax

If you prefer sticking with the year/month extraction approach, the fixed syntax (with the missing $ added to expr) works perfectly in PyMongo. While we still use $and here, the core fix was resolving the missing dollar sign on expr:

match_stage = {
    "$match": {
        "$expr": {
            "$and": [
                {"$eq": [{"$year": "$timestamp"}, 2016]},
                {"$eq": [{"$month": "$timestamp"}, 1]}
            ]
        }
    }
}

This version will run without errors in your Python script, as PyMongo correctly parses the $expr operator and the nested $and conditions now.

内容的提问来源于stack exchange,提问作者Rachel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:24:11