查找包含特定值的数组的文档 [英] Find document with array that contains a specific value
问题描述
如果我有此架构...
If I have this schema...
person = {
name : String,
favoriteFoods : Array
}
...,其中favoriteFoods
数组填充有字符串.我怎么能找到所有以猫鼬为食的人?
... where the favoriteFoods
array is populated with strings. How can I find all persons that have "sushi" as their favorite food using mongoose?
我希望有以下类似的东西:
I was hoping for something along the lines of:
PersonModel.find({ favoriteFoods : { $contains : "sushi" }, function(...) {...});
(我知道mongodb中没有$contains
,只是在知道解决方案之前先解释了我期望找到的内容)
(I know that there is no $contains
in mongodb, just explaining what I was expecting to find before knowing the solution)
推荐答案
由于favouriteFoods
是一个简单的字符串数组,因此您可以直接查询该字段:
As favouriteFoods
is a simple array of strings, you can just query that field directly:
PersonModel.find({ favouriteFoods: "sushi" }, ...);
但是我也建议在您的模式中使字符串数组显式显示:
But I'd also recommend making the string array explicit in your schema:
person = {
name : String,
favouriteFoods : [String]
}
相关文档可在此处找到: https://docs.mongodb.com /manual/tutorial/query-arrays/
The relevant documentation can be found here: https://docs.mongodb.com/manual/tutorial/query-arrays/
这篇关于查找包含特定值的数组的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!