What should the following two mongoDB collections do?
There are two sets:
Collection:categories
:
{"category":"animal","category_id":"1"}
{"category":"fruit","category_id":"2"}
{"category":"sport","category_id":"3"}
Collection:details
, it does notcategory_id
This item:
{"id":"1","name":"apple","category":"fruit"}
{"id":"2","name":"pear","category":"fruit"}
{"id":"3","name":"football","category":"sport"}
{"id":"4","name":"basketball","category":"sport"}
{"id":"5","name":"cat","category":"animal"}
{"id":"6","name":"dog","category":"animal"}
Question:
I want to putdetails
Addcategory_id
Item whose value iscategories
Corresponding tocategory_id
Value. What should we do?
This is a reference problem between collections. The solution code is as follows.
fruit=db.categories.findOne({"category":"fruit"}) db.details.updateMany({"category":"fruit"},{$set:{"category_id":fruit.categsory_id}})
The above code adds the category_id item to all {“category”:”fruit”} items in details, and its value is the category_id value corresponding to {“category”:”fruit”} items in categories.
Adding category_id to the rest of details is the same, just replace the part of fruit with animal and sport.
Cursor upgrade …
db.details.find().forEach( (x)=> { db.categories.find().forEach( (y)=> { if(y.category===x.category){ db.details.updateMany({"category":x.category},{$set:{"category_id":y.category_id}}) } }) })