开发者

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:

  1. 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."
  2. The correct order for $gt (and friends: $gte, $lt, $lte) is field: {$operator: value}, like:

    db.mycollection.find({"goals.goalID": {"$gt": 201}})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜