0

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.

mushroom
  • 1,909
  • 3
  • 16
  • 33

1 Answers1

0

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?

Community
  • 1
  • 1
pennstatephil
  • 1,593
  • 3
  • 22
  • 43
  • What happens if one car can be owned by two users? Do you have to update both users' cars or would updating one update the other? – mushroom May 14 '14 at 20:08
  • 1
    you could use the ID strategy I outlined, or yes, just update each instance of that car. alternatively, if you cared more about searching by car than owner, you could reverse it and embed the list of owners in each car entry...but if owner information changed, you would again have to update each instance. – pennstatephil May 14 '14 at 20:10
  • @mushroom added a link to a really good question about embedding vs referencing, you may want to check it out :) – pennstatephil May 14 '14 at 20:53