I am struggling with array matching and getting multiple records back.

"players" : [
        "pname" : "player_4",
        "loc" : [ -2.2, 1, 0]
        "pname" : "player_2",
        "loc" : [ 9, 1, 5 ]

Now assuming above data,

How do I project correctly where I get all the "loc" records that match the criterion?

Let's say loc.0 <15 should give both records, loc.0>0 should only give "player_2" etc.

I tried "players", "players.$". Without the $ I get all the data in "players". With the $, I get the first match. Obviously I am missing something big somewhere.

My trials below:

db.worlds.find({"name":"w1", "players.loc.0":{$lt:5}},{"players":1})

db.worlds.find({"name":"w1", "players.loc.0":{$lt:15}},{"players":1})

db.worlds.find({"name":"w1", "players.loc.0":{$lt:15}},{"players.$":1})

This is on Mongo 3.6.3.

  • There's a little bit of nuance here depending on what the end goal is. Is the goal to return the entire document, or only the embedded document in the 'players' array that matches the filter criteria? – Adam Harrison Dec 28 '18 at 22:52

Maybe you can try with $elemMatch : https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.