MongoDB: Filter documents against array length
5 May 2023 (Updated 14 February 2024)
Find by array length
// Find all records that have 2 employees
db.Firm.find({ employees: { "$size": 2 }})
Using $where
(not efficient)
Not as efficient but useful when you’re querying using the Mongo shell:
Find all documents that have more than 5 employees
db.Firm.find({ $where: "this.employees.length > 5"})
Using $exists
(efficient)
// Find all records that have at least 2 employees
db.Firm.find({ 'employees.1': { $exists: true } })
Tagged:
MongoDB
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment