简体   繁体   English

MongoDB Java查找文档并过滤数组字段(删除不符合条件的数组数据)

[英]Mongodb java find document and filter an array field (delete array data that don't match a condition)

I try to request a Collection but impossible to filter the embedded array. 我尝试请求一个Collection,但是无法过滤嵌入式数组。 I would like to get every Documents in the Collection that match {"players.nick" : nick } and filter the 'players' array to get only the searched player inside. 我想获取集合中所有匹配{“ players.nick”:nick}的文档,并过滤'players'数组以仅获取搜索到的玩家。

Here is the intial Document : 这是初始文件:

{"_id":2000,"type":3,"prizepool":6520.5,"name":"XXX","start":1515701700,"end":1515719580,"buyin":2.25,"rake":0.5,"prize":0,"bounty":2.25,"players":[{"nick":"player1","rank":1,"cash":660.85,"kill":468.64,"ticket":0,"reentry":0},{"nick":"player2","rank":2,"cash":430.35,"kill":101.31,"ticket":0,"reentry":0},{"nick":"player3","rank":3,"cash":312.98,"kill":72.26,"ticket":0,"reentry":0},{"nick":"player4","rank":4,"cash":237.99,"kill":27.15,"ticket":0,"reentry":1}]}

And after requesting I would like to retrieve : 在请求后,我想检索:

{"_id":2000,"type":3,"prizepool":6520.5,"name":"XXX","start":1515701700,"end":1515719580,"buyin":2.25,"rake":0.5,"prize":0,"bounty":2.25,"players":[{"nick":"player1","rank":1,"cash":660.85,"kill":468.64,"ticket":0,"reentry":0}}

Does anyone know how to do that in a java way ? 有谁知道如何用Java方式做到这一点?

Thanks ! 谢谢 !

You can use below aggregation pipeline in java. 您可以在Java中使用以下聚合管道。

MongoClient mc = new MongoClient();
MongoDatabase db = mc.getDatabase(db);
MongoCollection col = db.getCollection(col);

For single match you can use $elemMatch projection 对于单场比赛,您可以使用$elemMatch投影

col.find().projection(Projections.fields(Projections.include("_id","type", "prizepool","name","start","end","buyin","rake","prize","bounty"),
                Projections.elemMatch("players", Filters.eq("nick", "player1"))));

For both single & multiple matches 对于单场和多场比赛

Bson filter = new Document("players", Document.parse("{\n" +
            "            $filter: {\n" +
            "               input: \"$players\",\n" +
            "               as: \"player\",\n" +
            "               cond: { $eq: [ \"$$player.nick\", \"player1\" ] }\n" +
            "            }\n" +
            "         }"));
Bson addFields = new Document("$addFields", filter);
col.aggregate(Arrays.asList(addFields));

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

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