I have two collections, Group and User. Originally, my Group document contained an array of User references. But I’ve changed my mapping so that Users now hold a reference to a Group. I am wondering how I can write a query to update all the existing User documents to reference the group that is currently referencing them, then remove any references on the groups.
I have two collections, Group and User. Originally, my Group document contained an array
Share
I didn’t notice the language you are using at first – I had to do something very similar in Python so here is my example code:
Basically, for every user, I look in groups to find a list of groups which contain userId in the array users, and I make a list called groups in u and when I save it adds an array of groups to users document.
Should be not hard to do it in PHP
$users = $db->users;
$groups = $db->groups;
// find all users
$ucursor = $users->find();
// iterate through users, find groups which have the user,
// update user with array of groups
foreach ($ucursor as $u) {
$gcursor = $groups->find( … );
foreach ($gcursor as $g) {
…
}
}
But this seems like a one time operation, you could do it in mongo shell using something similar to: