假設我有兩個名為“食譜”和“配料”的集合,它們如下所示
食譜
{"RecipeID" : 000, "recipeName" : "Ramen", "IngredientIds" : [101, 103] }
{"RecipeID" : 001, "recipeName" : "FireNoodle", "IngredientIds" : [102, 103] }
原料
{ "IngredientId" : 101, "MoreData" : { "Details" : "This is details for 101"} }
{ "IngredientId" : 102, "MoreData" : { "Details" : "This is details for 102"} }
{ "IngredientId" : 103, "MoreData" : { "Details" : "This is details for 103"} }
如何在一次查詢中獲取所有資料,包括成分中的資料,而不是進行兩次查詢?我想以以下格式獲取資料,假設我查詢 RecipeID 的資料:000 并且我想得到以下結果。
{
"RecipeID" : 000,
"recipeName" : "Ramen",
"IngredientIds" : [
{ "IngredientId" : 101, "MoreData" : { "Details" : "This is details for 101"} },
{ "IngredientId" : 103, "MoreData" : { "Details" : "This is details for 103"} }
] }
uj5u.com熱心網友回復:
您需要$lookup使用管道。
db.Recipes.aggregate([
{
$match: {
"RecipeID": "000"
}
},
{
"$lookup": {
"from": "Ingredients",
"let": {
ingredientIds: "$IngredientIds"
},
"pipeline": [
{
$match: {
$expr: {
$in: [
"$IngredientId",
"$$ingredientIds"
]
}
}
},
{
$project: {
_id: 0
}
}
],
"as": "IngredientIds"
}
},
{
$project: {
_id: 0
}
}
])
示例 Mongo Playground
uj5u.com熱心網友回復:
db.Recipes.aggregate([
{
$match: { "RecipeID": "000" }
},
{
$lookup: {
from: "Ingredients",
localField: "IngredientIds",
foreignField: "IngredientId",
as: "IngredientIds"
}
},
{
$unset: [ "_id", "IngredientIds._id" ]
}
])
mongoplayground
uj5u.com熱心網友回復:
使用$lookup查找陣列,無需展開或任何額外操作
db.recipe.aggregate([
{
$match: {
"RecipeID": 0,
"recipeName": "Ramen"
}
},
{
$lookup: {
from: "ingredents",
localField: "IngredientIds",
foreignField: "IngredientId",
as: "IngredientIds"
}
},
{
$project: {
_id: 0,
RecipeID: "$RecipeID",
recipeName: "$recipeName",
IngredientIds: {
IngredientId: 1,
MoreData: 1
}
}
}
])
mongodb_playground_link
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431818.html
標籤:mongodb 天蓝色 聚合框架 天蓝色宇宙数据库 天蓝色 cosmosdb-mongoapi
