Say if there’re two simple Mongo documents, Person and Class. Person references Class to model a many-to-many this-person-takes-these-classes relationship. How do I find the person that is not registered in ANY classes (that has no references to any Class)?
I tried the following but didn’t seem to work:
db.people.find({"class": {$exists: false}});
The above returns all the people, even the ones that are taking classes.
Appreciate any input. Thanks!
First you have to define how this is modeled. There are three ways to do this with MongoDB.
Based on your query, it looks like you have #3, but that is not a given.
This will be very specific to how your data is actually stored in the DB.
Let’s say that
peoplecontains an array of references toclasses, your data will probably look like this:In this case “Steve” clearly has no classes. Your query is looking for
peoplewhereclassesdoes not exist. But in this case,classesdoes exist, it’s just empty.If your data looks like this, you probably want to use the
[$size][1]operator.