2

I have a MongoDB Collection like this, containing details of game players:

{
    ...
    "fields" : {
            "playername" : "Koala",
            ...
    }
    ...
}

And I want to get the IDs of the players in an array. So, for example, I do this:

// players: ["Koala", "Cactus"]
Criteria base = Criteria.where("fields.playername").in(players);
DBObject match = base.getCriteriaObject();
List<?> userDetailIds = playersCollection.distinct("_id", match);

Great, I have a list (com.mongodb.BasicDBList) of ObjectId objects (org.bson.types.ObjectId). But now I want to use that list in a new $in query, for example, get all the badges of those players. The Badges Collection:

{
        "badgeName": "MongoDB Killer", 
        "userDetailID" : "525c4be1975ac2a8f4a64c6f"
        ...
}

In Java:

mongo.find(Query.query(Criteria.where("userDetailID").in(userDetailIds)), Badges.class);

This doesn't work, because userDetailIds contains ObjectId objects and userDetailID is a String field. How can I use the BasicDBList as $in parameter? OR: Can I get an array of String IDs instead of ObjectIds?

Thanks!

PD. I don't want to iterate over the list to convert it to a List<String>.

Steven Carlson
  • 925
  • 1
  • 10
  • 25
Roi
  • 188
  • 1
  • 2
  • 7

1 Answers1

0

Use the toHexString() method which converts the ObjectId instance into a 24-byte hexadecimal string representation:

List<ObjectId> objIds = playersCollection.distinct("_id", match);
List<String> userDetailIds = new ArrayList<String>();
for (ObjectId objId : objIds) {
    userDetailIds.add(objId != null ? objId.toHexString() : null);
}

mongo.find(Query.query(Criteria.where("userDetailID").in(userDetailIds)), Badges.class);
chridam
  • 100,957
  • 23
  • 236
  • 235
  • Hi, thanks! But I'm looking for a solution that does not need to iterate over `objIds`. Can I get a `List` instead of `List`? Is there a way to use `objIds` directly in the second query? – Roi Nov 06 '15 at 15:43