Mongo查询数组中的嵌套字段。

时间:2016-05-09 00:51:28

标签: mongodb

我有一个包含以下结构的文档:{_id: 'fkwjefioew', genres: [{_id: 'fewkjfewf', 'name': "Shooter"}, {...}, ...]} 我需要能够使用mongo' s $来查询doc是否具有传递参数的类型名称。例如,如果我传递了" Shooter"的参数。对于查询,我希望所有文档中该文档generes数组中的一个对象保存名称" Shooter"。实现这一目标最简单的方法是什么?谢谢!

1 个答案:

答案 0 :(得分:1)

您可能希望使用$elemMatch

{"genres": { "$elemMatch" :  {"name": "Shooter"} } }
// or
{"genres": { "$elemMatch" :  {"name": { "$in": ["Shooter"] } } } }

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

你也可以使用mongodb点表示法,它会像你一样工作,除了:

{"genres.name": "Shooter"}
// or
{"genres.name": { "$in": ["Shooter"]}}

如果genres是一个数组,Mongodb知道如何解释这个。 请记住,点符号查询有点模棱两可,因为如果name属性不是数组,它也将匹配genres属性。例如,此文档将匹配:

{"genres": { "name": "Shooter" } }

在所有情况下,您都可以索引name数组中的genres属性,索引将用于查找。

db.collection.createIndex({'genres.name': 1})

https://docs.mongodb.com/manual/reference/glossary/#term-dot-notation

https://docs.mongodb.com/manual/reference/operator/query/in/

相关问题