问题描述
如果我有这个架构...
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?
我希望得到以下内容:
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" }, ...); // favouriteFoods contains "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/
这篇关于使用包含特定值的数组查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!