MongoDB: Filter documents against array length
5 May 2023 (Updated 5 May 2023)
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 recoreds that have at least 2 employees
db.Firm.find({ 'employees.1': { $exists: true } })
Tagged:
MongoDB