目标
使用MongoDB中的引用进行有效搜索。
背景
我在孟戈有个Smoothie数据库。smoothie是一个引用了Food对象的对象,它的表示方式如下:
{
name: "Red Velvet Cake",
ingredients: [{
food_id: "strawberry_raw",
//other really cool fields
},
//other ingredients
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
}现在,Food对象由以下示例表示:
{
"_id": "strawberry_raw",
"name": "strawberries",
//other really cool fields
}问题
考虑到这些模式,我要确保Smoothie对象知道构建它的所有Food对象。由于每个Smoothie对象最多将有6或7个食物对象,我相信这是最好的选择,因为它遵循MongoDB最小基数原理。
但是,现在我想允许使用以下功能:
我不知道如何用MongdoDB来做这件事。
示例
下面的例子说明了我想要的。
想象一下我有以下食物:
let foods = [{
"_id": "strawberry_raw",
"name": "strawberries"
}, {
"_id": "honeydew_melon_raw",
"name": "honeydew melon"
}, {
"_id": "coconut_milk",
"name": "homemade coconut milk"
}];以及以下几点:
let smoothies = [
{
name: "Coco Berry",
ingredients: [
{ food_id: "strawberry_raw" },
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
},
{
name: "Tropical Melon",
ingredients: [
{ food_id: "honeydew_melon_raw"},
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 51"
}];如果使用“椰子、草莓”一词进行搜索,功能将返回:
我尝试了什么,我需要什么
我知道,要想搜索“椰子”,返回一个名为“椰子奶”的食物,我必须在“食物收藏”中索引这些名字,我就是这么做的。
我还搜索了一下,我发现我可能需要使用$lookup,但是,我不知道如何从这一点出发。我该怎么做?
发布于 2016-11-15 18:07:03
我认为没有必要添加一个连接或索引,您可以使用$regex,让我试试我的手,考虑您的收藏‘
db.collection.find({ingredients : {$elemMatch : {$or :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})`
您的第二个查询
db.collection.find({ingredients : {$elemMatch : {$and :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})`
https://stackoverflow.com/questions/40613927
复制相似问题