MongoDB AND/OR组合查询无结果问题排查及语句修正求助
Let's break down why your query isn't returning results and fix it step by step.
The Core Problem: Mixed-Up Logical Operators
Your original query uses $and to combine two conditions:
db.Test.find({ $and : [{$or: [{"Name": "Aman"}, {"Name": "Ishu"}]} ,{"Id": "2"}] });
This tells MongoDB to only return documents that satisfy both requirements at the same time:
- Name is either "Aman" or "Ishu" AND Id equals "2"
But your stated goal is to get documents where either Id=2 OR Name is Aman/Ishu. You’ve inverted the logical structure here, which is why you’re getting no results (it’s unlikely any of your docs meet both conditions simultaneously).
Corrected Query Options
Here are two clean, correct ways to write the query that aligns with your actual requirement:
Option 1: Explicit $or with Individual Conditions
This directly maps to your "Id=2 OR Name=Aman OR Name=Ishu" logic:
db.Test.find({ $or: [ {"Id": "2"}, {"Name": "Aman"}, {"Name": "Ishu"} ] });
Option 2: Use $in for Conciseness
Since you’re checking the Name field against multiple fixed values, using $in makes the query cleaner and easier to maintain:
db.Test.find({ $or: [ {"Id": "2"}, {"Name": {$in: ["Aman", "Ishu"]}} ] });
One Final Check: Data Type Matching
If you still get no results after fixing the logic, double-check the data type of your Id field. If your documents store Id as a numeric value (e.g., 2 instead of "2"), you’ll need to remove the quotes in your query:
db.Test.find({ $or: [ {"Id": 2}, // No quotes here if Id is stored as a number {"Name": {$in: ["Aman", "Ishu"]}} ] });
MongoDB enforces strict type matching, so a string "2" won’t match a numeric 2 value.
内容的提问来源于stack exchange,提问作者Amandeep Kochhar

