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

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.

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 ?

Thanks !

解决方案

You can use below aggregation pipeline in java.

MongoClient mc = new MongoClient();

MongoDatabase db = mc.getDatabase(db);

MongoCollection col = db.getCollection(col);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值