Mongodb Java查找文档并过滤数组字段(删除不符合条件的数组数据) [英] Mongodb java find document and filter an array field (delete array data that don't match a condition)
本文介绍了Mongodb Java查找文档并过滤数组字段(删除不符合条件的数组数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试请求一个Collection,但是无法过滤嵌入式数组.我想获取集合中与{"players.nick":nick}相匹配的所有文档,并过滤'players'数组以仅获取搜索到的玩家.
I try to request a Collection but impossible to filter the embedded array. 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.
以下是初始文档:
{"_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}}
有人知道怎么用Java方式做到这一点吗?
Does anyone know how to do that in a java way ?
谢谢!
推荐答案
您可以在Java中使用以下聚合管道.
You can use below aggregation pipeline in java.
MongoClient mc = new MongoClient();
MongoDatabase db = mc.getDatabase(db);
MongoCollection col = db.getCollection(col);
对于单场比赛,您可以使用$elemMatch
投射
For single match you can use $elemMatch
projection
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));
这篇关于Mongodb Java查找文档并过滤数组字段(删除不符合条件的数组数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文