MongoDB analytics active user count always 0 when country filter applied
Problem
An analytics dashboard shows correct total active user counts but returns 0 when filtering by country. The query uses `{ _id: { $in: userIds }, _id: { $in: countryUserIds } }` — a JavaScript object with two identical `_id` keys. The second key overwrites the first, so only the country filter is applied, but the country user list includes all user types (drivers, admins), not just the user type being counted.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Replace overlapping _id keys with $and to compose multiple conditions
When a MongoDB query object has two conditions on the same field `_id`, the second overwrites the first in JavaScript. Using $and forces both conditions to be evaluated.
Trust Score
7 verifications
- 1
Wrap conflicting conditions in $and
Fix the query builder:
javascript// ❌ Duplicate _id key — second overwrites first const query = { _id: { $in: allUserIds }, _id: { $in: countryUserIds }, // overwrites line above } // ✅ $and enforces both conditions const query = { $and: [ { _id: { $in: allUserIds } }, { _id: { $in: countryUserIds } }, ] } - 2
Also ensure the user type filter is applied
Make sure countryUserIds only contains the user type you are counting (e.g. type: "user", not drivers or admins).
Validation
Analytics count with country filter returns the same result as filtering the full list manually.
Verification Summary
Sign in to verify this fix
Environment
- Product
- MongoDB
- Environment
- production
Submitted by
Alex Chen
2450 rep