简体   繁体   English

Java MongoDB如何使用BasicDBList作为$ in参数

[英]Java MongoDB how to use BasicDBList as $in parameter

I have a MongoDB Collection like this, containing details of game players: 我有一个这样的MongoDB Collection,其中包含游戏玩家的详细信息:

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

And I want to get the IDs of the players in an array. 我想以数组的形式获取玩家的ID。 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 ). 太好了,我有一个列表( com.mongodb.BasicDBList的) ObjectId对象( 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. 但是现在我想在一个新的$in查询中使用该列表,例如,获取那些玩家的所有徽章。 The Badges Collection: 徽章收藏:

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

In Java: 在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. 这不起作用,因为userDetailIds包含ObjectId对象,而userDetailIDString字段。 How can I use the BasicDBList as $in parameter? 如何使用BasicDBList作为$in参数? OR: Can I get an array of String IDs instead of ObjectId s? 或者:我可以获取String ID数组而不是ObjectId吗?

Thanks! 谢谢!

PD. PD。 I don't want to iterate over the list to convert it to a List<String> . 我不想遍历列表以将其转换为List<String>

Use the toHexString() method which converts the ObjectId instance into a 24-byte hexadecimal string representation: 使用toHexString()方法将ObjectId实例转换为24字节的十六进制字符串表示形式:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM