简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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