When searching for records with non-empty array fields in MongoDB, you can use the $ne (not equal) operator to query documents where the array field is not equal to an empty array. The $ne operator helps filter documents containing at least one element in the array field. Here is a query example:
javascriptdb.collection.find({ "arrayField": { "$ne": [] } });
In this query, arrayField represents the name of the array field you want to check, $ne is the query operator, and [] represents an empty array. This query returns all documents where the arrayField field is not an empty array.
For example, suppose you have a collection named students containing an array field named courses to store selected courses. To find students who have selected at least one course, use the following query:
javascriptdb.students.find({ "courses": { "$ne": [] } });
This returns all student documents where the courses field has at least one element (i.e., at least one course selected).
If you also want to ensure the courses field exists (not just non-empty), combine the $exists operator with $ne:
javascriptdb.students.find({ "courses": { "$exists": true, "$ne": [] } });
This query returns only documents where the courses field actually exists and the array is not empty.