如果得到以下数据库结构:
{ "_id" : "rv8MgKMB9qvrcoruW", "object" : "M5ZMiaqPQYP6Pv45y", "matches" : { "mbGLv9hiJJeyEcSoK" : "1", "hTcs5PYp5bXruZSTL" : "1" } }
{ "_id" : "2jksvGbg7fkguECRB", "object" : "M5ZMiaqPQYP6Pv45y", "matches" : { "mbGLv9hiJJeyEcSoK" : "2", "hTcs5PYp5bXruZSTL" : "2" } }
{ "_id" : "a5Ea5evtXkYrcjtLa", "object" : "M5ZMiaqPQYP6Pv45y", "matches" : { "JZKoX3B8gqiwotphb" : "3", "hTcs5PYp5bXruZSTL" : "3" } }
{ "_id" : "RsLhwDS5ERYxERAjX", "object" : "M5ZMiaqPQYP6Pv45y", "matches" : { "mbGLv9hiJJeyEcSoK" : "4", "JZKoX3B8gqiwotphb" : "4" } }
我喜欢用一个特定的对象和一个匹配的特定键值对来获取数据集。
例如:我想获取“object”:“m5zmiaqpqyp6pv45y”的数据集,其中有一个字典集“jzkox3b8gqiwotphb”:“3”。
因此在这种情况下,输出应该是:
{ "_id" : "a5Ea5evtXkYrcjtLa", "object" : "M5ZMiaqPQYP6Pv45y", "matches" : { "JZKoX3B8gqiwotphb" : "3", "hTcs5PYp5bXruZSTL" : "3" } }
我已经尝试了数百种组合,但目前仍坚持:
db.Matches.find ({ object: 'M5ZMiaqPQYP6Pv45y', matches: { mbGLv9hiJJeyEcSoK: { '$exists': true, $in: '3' } } })
最佳答案
使用dot notation访问子文档的字段:
db.Matches.find({object: 'M5ZMiaqPQYP6Pv45y', 'matches.JZKoX3B8gqiwotphb': '3'})
关于mongodb - MongoDB:检查嵌套键值对是否存在,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18232924/