[英]$lookup search Mongodb
使用MongoDB中的引用進行有效搜索。
我在Mongo上有一個冰沙數據庫。 思慕雪是一個引用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"
}
現在,一個食物對象由以下示例表示:
{
"_id": "strawberry_raw",
"name": "strawberries",
//other really cool fields
}
考慮到這些模式,我確保一個Smoothie對象知道構建它的所有Food對象。 由於每個居安思危型對象最多包含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
,但是,我不知道如何從此開始。 我該怎么做 ?
我認為不需要添加聯接或索引,您可以使用$ regex,讓我嘗試一下,考慮將smothie作為您的收藏集`
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")}]}}})
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.