Question

I'm a new user to MongoDB.

When I do a find() on a db.users, I get back an object like such:

{"_id" : ObjectId("5373c8779c82e0955aadcddc"), "username": "example"}

How do I link this document to another document? I'm using the command line mongo shell.

For example, I want to associate a person in db.person with an attribute owner in a car object in db.car.

Was it helpful?

Solution

so it sounds like you're trying to do a join, which mongo does not support. what it does support is embedding. so, based on what you're trying to do, you could embed a list of cars that a person owns... for example:

{
    id: (whatever),
    username: phil,
    cars: [
             {make: honda, model: civic, mileage: 44000},
             {make: ford, model: focus, mileage: 56000}
          ]
}

or, you could link to a list of IDs in your car collection:

{
    id: (whatever),
    username: phil,
    cars: [
             123,
             456
          ]
}

however this is less efficient, since you'll have to do more finds to get each car's info-- which is why embedding rocks!

This is described in detail here: MongoDB relationships: embed or reference?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top