Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MongoDB for multiple ObjectIDs in Array

I have a collection "users" in my Database. A user can be a member of several teams.

I am using an Array to reference the team IDs.

{ _id: ObjectId("552544fd600135861d9e47d5)", 
  name : "User1",
  teams: [
        "5527a9493ebbe2452666c238",
        "5527b1be3371e3a827fa602c"
    ]
}

The teams are nothing more than a collection of:

{ _id: ObjectId("5527a9493ebbe2452666c238"),
  name: "Team 1"
}
{ _id: ObjectId("5527b1be3371e3a827fa602c"),
  name: "Team 2"
}

Now I want to get the names of all the teams in which the user is a member.

I have only found the way of querying it this way:

db.teams.find(
   {_id:{$in:
      [ObjectId("5527a9493ebbe2452666c238"),
      ObjectId("5527b1be3371e3a827fa602c")]
   }})

To do this, I would need to create an array specifically for this query. I would rather try to avoid this, because I already have the IDs available as an array in the string format. Something like this would be great:

db.teams.find(
   {_id:{$in:  
          ["5527a9493ebbe2452666c238",
          "5527b1be3371e3a827fa602c"]  // Strings here, not ObjectIDs
   }})

But this does not work. Is there any comfortable way of querying an ObjectID with a set of string IDs?

Thanks & regards Rolf

like image 332
Rolf Beh Avatar asked Feb 10 '23 11:02

Rolf Beh


1 Answers

You could use a combination of mongodb's findOne() and find() cursor methods together with the native JavaScript map method to first get the team id's for a specific user (which will be a string array), then use the map function to map the teams' string id's array to an ObjectId's array, and finally query the teams collection with the resulting array as the $in operator expression:

var teams = db.users.findOne({"name": "User1"}).teams;
var obj_ids = teams.map(function (item){ return ObjectId(item)});
db.teams.find({ "_id": { "$in": obj_ids } });

Output:

/* 0 */
{
    "_id" : ObjectId("5527a9493ebbe2452666c238"),
    "name" : "Team 1"
}

/* 1 */
{
    "_id" : ObjectId("5527b1be3371e3a827fa602c"),
    "name" : "Team 2"
}
like image 135
chridam Avatar answered Feb 18 '23 23:02

chridam