1

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 !

0

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot ! It works perfectly... I was working on it the entire day... You rock !
@DavidB if this answer work for you "accept" it, that's the way to thank on SO and it also the correct indication for other users that you solved it using this. (never add solved to title of question)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.