下面这两个mongoDB集合的操作应该怎么做呢?
有两个集合:
Collection:categories
:
{"category":"animal","category_id":"1"}
{"category":"fruit","category_id":"2"}
{"category":"sport","category_id":"3"}
Collection:details
,它没有category_id
这一项:
{"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"}
问题:
我想把details
中的每一条加上category_id
项,它的值就是categories
中对应的category_id
值。应该怎么做呢?
这属于集合间的引用问题,解决办法代码如下。
上述代码做到了为details中的所有的{"category":"fruit"}项加上category_id项,它的值就是categories中的{"category":"fruit"}项对应的category_id值。
为details中剩余的添加category_id是同理的,只需要将fruit的部分替换成animal和sport即可。
游标升级版...