简体   繁体   中英

mongodb - one document in many collections

I'am looking for a good solution on MongoDB for this problem:
There are some Category's and every Category has X items.
But some items can be in in "many" Category's!

I was looking for something like a symbolic link on Unix systems but I could't not find it.

What i thought is a good idea is:
"Category1/item1" is the Object and "category2/item44232" is only a reference to "item1" so when i change "item1" it also changes "item44232".

I looked into the MongoDB Data models documentation but there is no real solution for this.

Thank you for your response !

In RDBMSs, you use a join table to represent one-to-many relationships; in MongoDB, you use array keys. For example each product contains an array of category IDs, and both products and categories get their own collections. If you have two simple category documents

{ _id: ObjectId("4d6574baa6b804ea563c132a"),
title: "Epiphytes"
}

{ _id: ObjectId("4d6574baa6b804ea563c459d"),
title: "Greenhouse flowers"
}

then a product belonging to both categories will look like this:

{ _id: ObjectId("4d6574baa6b804ea563ca982"),
name: "Dragon Orchid",
category_ids: [ ObjectId("4d6574baa6b804ea563c132a"),
ObjectId("4d6574baa6b804ea563c459d") ]
}

for more: http://docs.mongodb.org/manual/reference/database-references/

Try looking at the problem inside-out: Instead of having items inside categories, have the items list the categories they belong into.

You'll be able to easily find all items that belong to a category (or even multiple categories), and there is no duplication nor any need to keep many instances of the same item updated.

This can be very fast and efficient , especially if you index the list of categories. Check out multikey indexes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM