0

Being new to MongoDB environment, I have few questions regarding objectID. I imported two different json files into the database. For example, one of the collections is called animals. The other one contains the owner information like name, location, phone number.

Animals:{    
  animalType: "cat",
  age: 2 
}

Owner:{ 
  name: "John",
  location: "New York",
  phone: "974-234-2333"
}

I understand that MongoDB assigns two different objectID, because one they don't have an objectID assign and being two different collections it will randomly assign an objectID. How do I make sure that ObjectID in the owner collection is the same as the one in animals collections for me to be able to run join query?

Since both of the collections have different objectID, they can't really communicate with one another.

Joe
  • 41,484
  • 20
  • 104
  • 125
LooperBoy
  • 39
  • 4
  • How do you know which owner is associated with an animal in your source data? It looks like there is an `ownerID` or similar field missing from your `animals` collection. – Stennie Mar 07 '18 at 00:24
  • It sounds like you're trying to force a relational model into mongo. Why don't you use a relational db instead? – Jeff Storey Mar 07 '18 at 00:25
  • I'm just trying to learn MongoDB, so I just came up this example. Less just say the ownerId field doesn't exist at all. Instead, I want to use the objectId to make the relation between two collections. Is it possible for MongoDB to do this? – LooperBoy Mar 07 '18 at 00:43
  • If owner and animals are 1:1 (as they would have to be with the same unique `_id`) it would make more sense to colocate these in a single document (_embedding_ instead of _linking_). A more realistic model would be 1:many. In this case the best approach would depend on how many animals an owner would have (tens vs thousands) and how you commonly use the data (paginated versus fetching all results). The blog series [6 Rules of Thumb for Schema Design](https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1) is a good starting reference for modelling relationships. – Stennie Mar 08 '18 at 02:57

1 Answers1

0

You can put an _id field in your json, and that will be used as the object id. Alternatively, you can use any arbitrary field in the data as a "foreign key" to join the two collections (e.g. create a field called "ownerID" in the Animals collection.

However, when using a document store like mongo, you should rethink your data model. Mongo wasn't built for doing joins, though it does support it How do I perform the SQL Join equivalent in MongoDB?. I suggest reading up on how to model data in document databases.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406