Bryan
Bryan

Reputation: 3280

How to find MongoDB record that has a reference to another document?

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!

Upvotes: 2

Views: 1040

Answers (1)

Gates VP
Gates VP

Reputation: 45287

Person references Class to model a many-to-many this-person-takes-these-classes relationship.

First you have to define how this is modeled. There are three ways to do this with MongoDB.

  1. Intermediate table, similar to how this is done in SQL.
  2. Array of references on one collection.
  3. Array of references in both collections.

Based on your query, it looks like you have #3, but that is not a given.

How do I find the person that is not registered in ANY classes?

This will be very specific to how your data is actually stored in the DB.

Let's say that people contains an array of references to classes, your data will probably look like this:

{ _id: "John", classes: [ 'math', 'science', 'english' ] }
{ _id: "Mary", classes: [ 'computers', 'biology' ] }
{ _id: "Steve", classes: [ ] }

In this case "Steve" clearly has no classes. Your query is looking for people where classes does not exist. But in this case, classes does exist, it's just empty.

If your data looks like this, you probably want to use the [$size][1] operator.

Upvotes: 4

Related Questions