Rav*_*iya 7 mongodb mongodb-query aggregation-framework
我有两个文档,这些文档之间有 DBRef 关系。
{
"_id": 77,
"title": "Test title",
"status": "in-progress",
"reporter": {
"$ref": "User",
"$id": ObjectId("5daf022549a36e319879f357"),
"$db": "test"
},
"priority": "high",
"project": {
"$ref": "Project",
"$id": 30,
"$db": "gsc"
}
}
Run Code Online (Sandbox Code Playgroud)
用户文档:
{
"_id": ObjectId("5daf022549a36e319879f357"),
"username": "user1",
"email": "test@gmail.com",
"is_active": true,
"firstName": "user-1"
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下查询,但没有得到正确的结果
{
"_id": 77,
"title": "Test title",
"status": "in-progress",
"reporter": {
"$ref": "User",
"$id": ObjectId("5daf022549a36e319879f357"),
"$db": "test"
},
"priority": "high",
"project": {
"$ref": "Project",
"$id": 30,
"$db": "gsc"
}
}
Run Code Online (Sandbox Code Playgroud)
如何执行JOIN?另外,想要同时记录所有数据吗? 我想要来自任务文档的数据并建议如何加入项目字段。
需要这样的结果:
{
"_id" : 77,
"title" : "Test title",
"status" : "in-progress"
"reporter" :
{
"_id" : ObjectId("5daf022549a36e319879f357"),
"username" : "user1",
"email" : "test@gmail.com"
"is_active" : true,
"firstName" : "user-1"
},
"priority" : "high",
"project" : {}
Run Code Online (Sandbox Code Playgroud)
一个简单的方法$lookup就可以解决问题。您只需reporter.$id向现场供应localField
db.task.aggregate([
{
"$lookup": {
"from": "user",
"localField": "reporter.$id",
"foreignField": "_id",
"as": "reporter"
}
},
{
"$unwind": "$reporter"
}
])
Run Code Online (Sandbox Code Playgroud)
这是Mongo游乐场供您参考。
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |