简体   繁体   中英

MongoDB - How does query for many-to-many relation work?

I am reading the book MongoDB in Action . I have a question about Chapter 4: Document-oriented data .

On Page 58 , the book gives an example for many-to-many relations. It gives Product document and Category document.

Product

product_1

product_2

Category

category_1category_2


My question

I understand the many-to-many association here. Basically, Product can have a key with array of Category _id, etc. So I am not trying to ask a question like this MongoDB Many-to-Many Association

My question is about Page 61 , where the book gives two example queries about querying the many-to-many relations. Here is the two queries:

两个问题

  1. What does => mean? I thought => only exists in Ruby driver usage.

  2. What is the category in category['_id'] ? Is it a collection?

  3. What is the product in product['category_ids'] ?

  4. How is the first query related to Gardening Tools category as described above the first query?

The book doesn't explain these two queries in details.

Can someone explain more about querying for many-to-many?

It does look like the author is using a driver's language other than the native MongoDB javascript mongo client. Also it would make sense since the book description says the author maintains both the C and Ruby Mongo drivers.

  1. Yes the => is a language driver specific notation. Not javascript. Seems to be just like saying: db.products.find({_id: aCategoryId}) . Its actually a Ruby Hash notation .

  2. The category in that example looks to represent just a category document that you have already retrieved. In this case, it would have been the doc for the Gardening Category. Its just saying "find all products where this category id is in the products category_ids array

  3. Similar to the previous question. product is a document you have retrieved already. The query is saying "find any category doc where its id is IN this products array of category ids.

  4. category would be the Gardening Category if you had retrieved it with something like: var category = db.category.findOne({slug: "gardening-tools"})

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