How to use $gt and $lt on embedded list in mongodb
I'm using pymongo and currently have a single collection. The collection holds documents representing matches in a football league. E开发者_运维技巧ach match has goals. Currently the goals are implemented as a list contained in the match object:
{'matchID':1000,
'goals':[{'goalID':200,'scorer':'A'},
{'goalID':201,'scorer':'B']}
]
}
{'matchID':1001,
'goals':[{'goalID':211,'scorer':'C'},
{'goalID':212,'scorer':'D']}
]
}
What I want to do is query for all goals with an ID higher than, say 201. What I would expect from the data above is that I would get goals 211 and 212.
How do I implement this in mongodb - I'm trying things like:
x = mycollection.find({'$gt':[{'match.goals.goalID':201}]})
but that isn't getting me anywhere. Should I be splitting goals into a separate collection and manually referencing instead? Once a goal is entered, it is never touched again - it will be read only.
You've got a couple of issues with that query:
- The correct dotted field name for the
goalID
elements of the objects nested in the arrays should be "goals.goalID
" -- that is, remove the preceding "match.
" The correct order for
$gt
(and friends:$gte
,$lt
,$lte
) isfield: {$operator: value}
, like:db.mycollection.find({"goals.goalID": {"$gt": 201}})
精彩评论