乐闻世界logo
搜索文章和话题

Find MongoDB records where array field is not empty

1个答案

1

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:

javascript
db.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:

javascript
db.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:

javascript
db.students.find({ "courses": { "$exists": true, "$ne": [] } });

This query returns only documents where the courses field actually exists and the array is not empty.

2024年6月29日 12:07 回复

你的答案