Mongoose查询:如何匹配数组含另一数组任意元素的文档
Got it, let's work through this for you. First, let's fix a couple of small issues from your original code, then land on the correct query for matching multiple order IDs.
1. Why Your Original Approach Needs Tweaks
Your initial query used $all—which checks if the array contains every single ID you pass in. That works great for a single ID, but not when you want to match any ID from a list. Also, putting $populate inside the query object isn't how Mongoose operates—populate is a method you chain after find, not part of the query conditions.
2. The Correct Query for Multiple Order IDs
To find all Combined documents where either done or notDone includes any ID from your list, swap $all for $in and keep using $or to cover both arrays. Here's the full working code:
First, define your list of order IDs (if you have string IDs, Mongoose will auto-convert them to ObjectIds, but you can explicitly cast them if you want):
const orderIds = ['60d21b4667d0d8992e610c85', '60d21b8967d0d8992e610c86']; // Example ID list // Optional: Explicitly cast strings to ObjectIds // const orderIds = ['your-id-1', 'your-id-2'].map(id => mongoose.Types.ObjectId(id));
Then run the query with proper population:
const matchingCombinedDocs = await Combined.find({ $or: [ { done: { $in: orderIds } }, // Match if `done` has ANY of the order IDs { notDone: { $in: orderIds } } // Match if `notDone` has ANY of the order IDs ] }) .populate('done notDone'); // Chain populate to load the referenced order documents
Breakdown of Key Changes
$in: This operator checks if the array contains at least one element from your list—exactly what you need for "any ID in the list" matching.$or: Ensures we check both thedoneandnotDonearrays for matches.- Proper
populate: Mongoose'spopulateis a query method, not part of the filter object. You can pass multiple fields as a space-separated string or an array.
Quick Side Note
If you ever need to match documents where done or notDone contains all IDs from your list, you'd switch back to $all—but for your current use case, $in is the right tool.
内容的提问来源于stack exchange,提问作者Rares P

