从参考模型[重复]中填充所有项目
此问题已经在这里有了答案:
- $lookup multiple levels without $unwind?1个答案
- Mongoose: deep population (populate a populated field)8个答案
假设User
,List
和ListItem
是集合,您应该可以使用$lookup
来完成此操作。
$lookup
查询:
Here is a live demo of the following query..
数据集:
db.users.aggregate([
{
$match: {
uniqueId: 1
}
},
{
$lookup: {
from: "lists",
localField: "uniqueId",
foreignField: "userId",
as: "lists"
}
},
{
$lookup: {
from: "listItems",
localField: "uniqueId",
foreignField: "userId",
as: "listItems"
}
}
])
结果:
db={ // Simulates a DB ********
"users": [ // Simulates a Collection ********
{
"firstname": "John",
"lastname": "Smith",
"email": "[email protected]",
"password": "password123",
"uniqueId": 1
},
{
"firstname": "Jane",
"lastname": "Doe",
"email": "[email protected]",
"password": "123password",
"uniqueId": 2
}
],
"lists": [ // Simulates a Collection ********
{
"userId": 1,
"name": "Johns List 1",
"items": [
11,
12,
13
]
},
{
"userId": 2,
"name": "Groceries",
"items": [
21,
22,
23
]
}
],
"listItems": [ // Simulates a Collection ********
{
"userId": 2,
"itemId": 21,
"title": "Apple",
"notes": []
},
{
"userId": 2,
"itemId": 22,
"title": "Banana",
"notes": []
},
{
"userId": 2,
"itemId": 23,
"title": "Strawberry",
"notes": []
},
{
"userId": 1,
"itemId": 11,
"title": "Oil Change",
"notes": []
},
{
"userId": 1,
"itemId": 12,
"title": "Pick Up Grandma",
"notes": []
},
{
"userId": 1,
"itemId": 13,
"title": "Go For Run",
"notes": []
}
]
}
从参考模型[重复]中填充所有项目
此问题已经在这里有了答案:
- $lookup multiple levels without $unwind?1个答案
- Mongoose: deep population (populate a populated field)8个答案
假设User
,List
和ListItem
是集合,您应该可以使用$lookup
来完成此操作。
$lookup
查询:
Here is a live demo of the following query..
数据集:
db.users.aggregate([
{
$match: {
uniqueId: 1
}
},
{
$lookup: {
from: "lists",
localField: "uniqueId",
foreignField: "userId",
as: "lists"
}
},
{
$lookup: {
from: "listItems",
localField: "uniqueId",
foreignField: "userId",
as: "listItems"
}
}
])
结果:
db={ // Simulates a DB ********
"users": [ // Simulates a Collection ********
{
"firstname": "John",
"lastname": "Smith",
"email": "[email protected]",
"password": "password123",
"uniqueId": 1
},
{
"firstname": "Jane",
"lastname": "Doe",
"email": "[email protected]",
"password": "123password",
"uniqueId": 2
}
],
"lists": [ // Simulates a Collection ********
{
"userId": 1,
"name": "Johns List 1",
"items": [
11,
12,
13
]
},
{
"userId": 2,
"name": "Groceries",
"items": [
21,
22,
23
]
}
],
"listItems": [ // Simulates a Collection ********
{
"userId": 2,
"itemId": 21,
"title": "Apple",
"notes": []
},
{
"userId": 2,
"itemId": 22,
"title": "Banana",
"notes": []
},
{
"userId": 2,
"itemId": 23,
"title": "Strawberry",
"notes": []
},
{
"userId": 1,
"itemId": 11,
"title": "Oil Change",
"notes": []
},
{
"userId": 1,
"itemId": 12,
"title": "Pick Up Grandma",
"notes": []
},
{
"userId": 1,
"itemId": 13,
"title": "Go For Run",
"notes": []
}
]
}
与本文相关的文章
评论列表 (0)
- 暂无评论